繁体   English   中英

从 Python 中的字符串中删除重复的尾随字符

[英]Removing repeated trailing characters from a string in Python

我有一个带有评论的字段。 一些评论只是“否”,但尾随有不同的“o”。 我想对这些评论进行转换,以便只返回“否”。 如何使用正则表达式实现此目的?

例如:

remove_trailing_os("noooooo")应该是 output "no"

remove_trailing_os("nooOOoooooooo")应该是 output "no"

您可以使用不区分大小写的反向引用:

import re
re.sub(r'(.)(?i:\1)+$', r'\1', "nooOOoooooooo", re.I)

output: 'no'

正则表达式:

(.)        # match a character
(?i:\1)+$  # match trailing case insensitive repeats of the character

您可以尝试加入

cc = "noooooo"
cc1= "nooOOoooooooo"
print(''.join(sorted(set(cc), key=cc.index)))
print(''.join(sorted(set(cc1.lower()), key=cc1.index)))

会给

no
no

也可以使用正则表达式

repeat_pattern = re.compile(r'(\w)\1*', flags=re.IGNORECASE)
d = repeat_pattern.sub(r"\1", cc)
d1 = repeat_pattern.sub(r"\1", cc1)
print(d)
print(d1)

也会给

no
no

这似乎类似于如何在第二次出现“”(空格)后删除所有字符

但本质上你想用o替换空间。 因此

## Assuming the two instances
t = 'noooooo'
t2 = 'nooOOoooooooo'
## Trying them on the two instances
t[:t.find('o',t.find('o')+1)]
t2[:t2.find('o',t2.find('o')+1)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM