[英]How can I use regex to find if a string has 2 specific characters and remove them if they are?
Basically, if I have a string (ex. 'ddbg') python should return 'bg' 基本上,如果我有一个字符串(例如“ ddbg”),python应该返回“ bg”
I am a little confused as to how to use the regex library for this task. 对于如何使用正则表达式库执行此任务,我有些困惑。
I have been able to find 1 d and get rid of it... but not 2. 我已经找到了1 d并摆脱了它...但是没有2。
I need to check if a string has only 2 d's and if so remove them. 我需要检查一个字符串是否只有2 d,如果是,请将其删除。
Try this: 尝试这个:
s = "dbdg"
res = re.findall("d", s)
if len(res) == 2:
s = s.replace("d", "")
Another way without regex (if you don't have to use regex). 没有正则表达式的另一种方式(如果您不必使用正则表达式)。 Strings are iterable so you can check the count of how many times something shows up in a list. 字符串是可迭代的,因此您可以检查列表中某项内容显示多少次。 If it shows up twice then use the str type replace method to remove it. 如果它出现两次,则使用str类型的replace方法将其删除。
s = "dbdg"
s = s.replace('d', '') if s.count('d') == 2 else s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.