简体   繁体   English

如何使用正则表达式查找字符串中是否包含2个特定字符,如果存在则将其删除?

[英]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.

相关问题 我如何使用正则表达式从字符串中删除重复的字符 - How I can use regex to remove repeated characters from string 如何使用正则表达式使用 Python 按字母顺序查找字符串? - How can I use Regex to find a string of characters in alphabetical order using Python? 我如何使用正则表达式获取两个字符内的字符串并删除该字符串内的某些字符 - how do i use regex to get a string inside two character and remove certain characters inside that string 如何使用正则表达式从字符串中删除所有非字母数字字符(“#”除外)? - How can I remove all non-alphanumeric characters from a string, except for '#', with regex? 字符串中的ASCII字符-如何删除它们 - ascii characters in a string-How to remove them 如何使用 python 中的正则表达式从多行字符串中删除特定字符 - How can I remove a specific character from multi line string using regex in python 找到字符串后如何从字符串中检索字符? - How can I retrieve characters from a string after finding them? 如何转换字符串和特定索引中的特定字符 - How can i convert specific characters in a string and in a specific index 在Python中,如何删除特定字符周围的字符? - In Python, how can I remove characters around a specific character? 如何删除 python 字符串中的所有“\”并将它们替换为“/”? - How can i remove all the "\" in a python string and replace them with "/"?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM