Skip to main content
 首页 » 编程设计

Python之用本身加上特殊字符替换字符串而不考虑大写和小写

2025年05月04日23softidea

给定一个字符串:

s = "abc, Abc, aBc, abc-def, abca" 

还有一句话:

w = "abc" 

我想按以下方式修改s:

!+abc+!, !+Abc+!, !+aBc+!, abc-def, abca

换句话说,我想替换所有 abc 的出现,无论其中的小写字母还是大写字母,它本身前面是 !+ ,后面是 +!.

我已经知道我的问题与这个问题非常相似: Match string in python regardless of upper and lower case differences

不过,它仍然略有不同。

目前我的解决方案很脏,无法正常工作:

s = "abc, Abc, aBc, abc-def, abca" 
w = "abc" 
if w in s: 
    s = s.replace(w, "!+"+w+"+!") 
if w.title() in s: 
    s = s.replace(w.title(), "!+"+w.title()+"+!") 

请您参考如下方法:

即使没有正则表达式也非常简单。

>>> ', '.join('!+{}+!'.format(x) if x.lower()==w else x for x in s.split(', ')) 
'!+abc+!, !+Abc+!, !+aBc+!, abc-def, abca' 

编辑:使用列表理解而不是生成器理解更快,所以

', '.join(['!+{}+!'.format(x) if x.lower()==w else x for x in s.split(', ')]) 

应该是首选。阅读this特别是 Raymond Hettinger 的问题和答案。