Lif*_*lex 2 python regex python-3.x
在将项目插入数据库之前,我尝试使用正则表达式来清理一些数据。我无法解决删除字符串末尾尾随特殊字符的问题。
如何编写此正则表达式以仅删除尾随特殊字符?
import re
strings = ['string01_','str_ing02_^','string03_@_', 'string04_1', 'string05_a_']
for item in strings:
clean_this = (re.sub(r'([_+!@#$?^])', '', item))
print (clean_this)
outputs this:
string01 # correct
string02 # incorrect because it remove _ in the string
string03 # correct
string041 # incorrect because it remove _ in the string
string05a # incorrect because it remove _ in the string and not just the trailing _
Run Code Online (Sandbox Code Playgroud)
rstrip您还可以使用字符串的特殊用途方法
[s.rstrip('_+!@#$?^') for s in strings]
# ['string01', 'str_ing02', 'string03', 'string04_1', 'string05_a']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2886 次 |
| 最近记录: |