我有一个字符串,s = 'sdfjoiweng%@$foo$fsoifjoi'
,我想用'bar'
替换'foo'
。
我尝试使用re.sub(r'\bfoo\b', 'bar', s)
和re.sub(r'[foo]', 'bar', s)
,但它们都没有起作用。我错在哪里了?
您可以直接替换它:
>>> import re
>>> s = 'sdfjoiweng%@$foo$fsoifjoi'
>>> print(re.sub('foo','bar',s))
sdfjoiweng%@$bar$fsoifjoi
它也能适用于以下更多的foo
出现情况:
>>> s = 'sdfjoiweng%@$foo$fsoifoojoi'
>>> print(re.sub('foo','bar',s))
sdfjoiweng%@$bar$fsoibarjoi
如果你只想替换字符串中第一次出现的foo
而不是所有foo
的出现,那么alecxe的答案正好做到了这一点。foo
,就像你的第二个例子一样。 - alecxere.sub()
而不是replace()
呢? - alecxe
re.sub(r'\bfoo\b', 'bar', s)
这里的\b
定义了单词边界 - 即单词字符(\w
)和非单词字符之间的位置,正好与您在sdfjoiweng%@$foo$fsoifjoi
字符串中匹配的foo
相对应。对我来说很有效:
In [1]: import re
In [2]: s = 'sdfjoiweng%@$foo$fsoifjoi'
In [3]: re.sub(r'\bfoo\b', 'bar', s)
Out[3]: 'sdfjoiweng%@$bar$fsoifjoi'
s ='sdfjoiweng%@$foo foo $fsoifjoi'
将无法正常工作。 - Geeocode您可以直接使用replace函数而不是使用正则表达式。
>>> s = 'sdfjoiweng%@$foo$fsoifjoifoo'
>>>
>>> s.replace("foo","bar")
'sdfjoiweng%@$bar$fsoifjoibar'
>>>
>>>
import re
s = 'thisis a test'
re.sub('\bthis\b|test','',s)
This gives:
'thisis a '
thisis this a
。你有什么解决办法吗? - Geeocodethisis this this a test
转换为 thisis that that a that
。 - Geeocodere.sub("\bthis\b|test", "Q", re.sub(" this ", " Q ", "thisis this is a test"))
。它是一个嵌套的van,就像我谈到的嵌套解决方案一样,但当然也可以是两行代码(就像我实际上做的那样)。结果是:thisis Q is a Q
。 - Geeocode
print re.sub(r'\bfoo\b', 'bar', s)
is correctly giving mesdfjoiweng%@$bar$fsoifjoi
- anubhavas
被就地修改?在 Python 中,字符串是不可变的。经过修改的新字符串将由re.sub
返回。 - jez