从字符串中删除结尾的特殊字符

时间:2018-12-18 16:17:33

标签: 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 _

3 个答案:

答案 0 :(得分:3)

您还可以使用特殊用途的字符串rstrip方法

[s.rstrip('_+!@#$?^') for s in strings]
# ['string01', 'str_ing02', 'string03', 'string04_1', 'string05_a']

答案 1 :(得分:2)

您需要一个词尾锚点$

 clean_this = (re.sub(r'[_+!@#$?^]+$', '', item))

Demo

答案 2 :(得分:1)

您可以重复字符类1次以上,否则只能替换1个特殊字符。然后声明字符串$的结尾。请注意,您不需要角色类周围的捕获组:

[_+!@#$?^]+$

例如:

import re
strings = ['string01_','str_ing02_^','string03_@_', 'string04_1', 'string05_a_']

for item in strings:
  clean_this = (re.sub(r'[_+!@#$?^]+$', '', item))
  print (clean_this)

请参见Regex demo | Python demo

如果您还想最后删除空白字符,则可以在字符类中添加\s

[_+!@#$?^\s]+$

Regex demo

相关问题