This article summarizes the Python method of simple filtering and deleting numbers. Share with you for your reference, as follows:
If you want to filter out characters that only contain numbers from a list containing numbers, Chinese characters, and letters, you can of course use regular expressions to complete it, but it's a bit too troublesome, so you can use a more clever way:
1、 Regular expression solving
import re
L =[u'Xiao Ming','xiaohong','12','adf12','14']for i inrange(len(L)):if re.findall(r'^[^\d]\w+',L[i]):
print re.findall(r'^\w+$',L[i])[0]
elif isinstance(L[i],unicode):
print L[I]
2、 Cleverly avoid regular expressions
L =['xiaohong','12','adf12','14',u'Xiaoming']for x in L:try:int(x)
except:
print x
3、 Use string built-in method
L =['xiaohong','12','adf12','14',u'Xiaoming']
# For python3, you can also use string.isnumeric()method
for x in L:if not x.isdigit():
print x
4、 Remove the numbers at both ends
If you just remove the numbers in a string that may contain numbers at both ends, you can use the built-in strip, as follows:
In [24]:import string
In [25]: astring ='12313213215just for 32 test 1306436'
In [26]: astring.strip(string.digits)
Out[26]:'just for 32 test '
In [27]: astring.rstrip(string.digits)
Out[27]:'12313213215just for 32 test '
In [30]: astring.lstrip(string.digits)
Out[30]:'just for 32 test 1306436'
# note
In [31]: astring
Out[31]:'12313213215just for 32 test 1306436'
In [32]: astring.strip('0123456')
Out[32]:'just for 32 test '
. When the char in strip([char]) is given, the characters at both ends will be intercepted until it is not in set(char), so there is no need to order, remember!
Example extension:
crazystring ='dade142.!0142f[., ]ad'
# Only keep numbers
new_crazy =filter(str.isdigit, crazystring)print(''.join(list(new_crazy))) #Output: 1420142
# Keep only letters
new_crazy =filter(str.isalpha, crazystring)print(''.join(list(new_crazy))) #Sleeping out: dadefad
# Keep only letters and numbers
new_crazy =filter(str.isalnum, crazystring)print(''.join(list(new_crazy))) #Output: dade1420142fad
# If you want to keep the number 0-9 and decimal point'.'Custom function
new_crazy =filter(lambda ch: ch in'0123456789.', crazystring)print(''.join(list(new_crazy))) #Output: 142.0142.
The results of the above code:
1420142
dadefad
dade1420142fad
142.0142.
So far, this article on how python filters numbers is introduced. For more related python how to filter digital content, please search for previous articles of ZaLou.Cn or continue to browse related articles below. Hope you will support ZaLou.Cn more in the future. !
Recommended Posts