[英]How can I use regex to find if a string has 2 specific characters and remove them if they are?
基本上,如果我有一个字符串(例如“ ddbg”),python应该返回“ bg”
对于如何使用正则表达式库执行此任务,我有些困惑。
我已经找到了1 d并摆脱了它...但是没有2。
我需要检查一个字符串是否只有2 d,如果是,请将其删除。
尝试这个:
s = "dbdg"
res = re.findall("d", s)
if len(res) == 2:
s = s.replace("d", "")
没有正则表达式的另一种方式(如果您不必使用正则表达式)。 字符串是可迭代的,因此您可以检查列表中某项内容显示多少次。 如果它出现两次,则使用str类型的replace方法将其删除。
s = "dbdg"
s = s.replace('d', '') if s.count('d') == 2 else s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.