简体   繁体   English

从字符串中删除所有内容。仅在其中保留数字

[英]Remove Everything from a string .. Only Leave Numbers in it

The string might be: 该字符串可能是:

JAIDK392**8'^+%&7JDJ0204İŞÇéS29487

I would like to remove everything from it but only leave behind numbers. 我想从中删除所有内容,但只留下数字。

A simple way to do this is with the regular expression library re : 一个简单的方法是使用正则表达式库re

>>> import re
>>> yourString = "JAIDK392**8'^+%&7JDJ0204İŞÇéS29487"
>>> numberOnlyString = re.sub('[^0-9]', '', yourString)
>>> print numberOnlyString
'39287020429487'

There's a way to do it without using any library. 有一种无需使用任何库即可完成此操作的方法。 You can use the built-in function ord to get the ASCII code of a character. 您可以使用内置函数ord获取字符的ASCII码。 Then you can parse every character in your string to check if it is a number (If it is its ASCII code should be between 47 and 58. 然后,您可以解析字符串中的每个字符以检查它是否为数字(如果为数字,则其ASCII码应在47到58之间。

 str = "JAIDK392**8'^+%&7JDJ0204İŞÇéS29487" output = [] for char in str: if 47 < ord(char) < 58: output.append(char) result=''.join(output) print result 

Regular expressions are great, but another way to do it would be: 正则表达式很棒,但是另一种方式是:

>>> import string
>>> digits_only = "".join(_ for _ in your_string if _ in string.digits)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从字符串中删除所有字符并仅在数据框中保留数字? - how to remove all characters from string and leave numbers only in dataframe? 删除所有内容,但保留数字和点 - Remove everything but leave numbers and dots 从字符串中删除除数字和小数之外的所有内容 - Remove everything but numbers and decimals from string 如何从字符串中删除所有内容并仅保留数字(比*** re.sub(&#39;[^ 0-9]&#39;,&#39;&#39;,str)***更快的东西)? - How to remove everything from a string and leave behind only digits ( something faster than *** re.sub('[^0-9]', '', str) ***)? 如何使用数字从字符串中删除所有内容以在某个点停止 - How to remove everything from a string using numbers to stop at a certain point 从字符串中仅删除括号之间的数字 - remove only numbers between brackets from a string 从字符串中删除“\\n”,但保留实际的换行符? - Remove "\n" from a string, but leave the actual linebreaks? 在 pyton 中使用正则表达式只在字符串中留下字母和数字 - Leave only letters and numbers in the string using a regex, in pyton 如何仅从 Pandas 列中的字符串中删除数字 - How to remove only numbers from a string in Pandas columns 如果字符串具有“仅数字”,则从 pandas dataframe 中删除行 - Remove rows from pandas dataframe if string has 'only numbers'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM