I have to filter a string variable by removing every character after 'U'.
For example:
1) having 075600U2
I should get 075600U
2) having 892009U24
I should get 892009U
I tried to do a for loop to replace every character after U as '' but I'm not getting any result
material = '075600U2'
for i in range((material.find('U')+1), len(material)):
material[i].replace('')
print(material)
I expect the output of '075600U', but the actual output is '075600U2'
Any idea?
In [34]: material = '075600U2'
In [35]: ''.join(material.partition("U")[:2])
Out[35]: '075600U'
In [36]: material = '075600U258'
In [37]: ''.join(material.partition("U")[:2])
Out[37]: '075600U'
In [38]: material = '075600'
In [39]: ''.join(material.partition("U")[:2])
Out[39]: '075600'
The re.sub
function comes in handy here:
material = '075600U2'
output = re.sub(r'(?<=U).*', '', material)
print(output)
This prints:
075600U
与其替换这些字符,不如将它们切成薄片?
material = material[:material.find('U')+1]
import re
replaced = re.sub('U[\d]*', 'U', material)
print(replaced)
output
075600U
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.