[英]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.