2024-04-27 11:15:09 发布
网友
给定字符串为:
s = "python is programming language p"
我想得到:
s = "2ython is 2rogramming language p"
所以,我想替换所有字母“p/p”,但前提是单词以它开头。你知道吗
我试过这样的方法:
re.sub(r'(^p)*', r'/', string), but it didn't help
你可以用
re.sub(r'\bp\B', '2', s, flags=re.I)
参见regex demo。你知道吗
如果您需要确保在p之后有一个字母,请使用
p
re.sub(r'\bp(?=[^\W\d_])', '2', s, flags=re.I)
见another regex demo。你知道吗
细节
\b
P
re.I
\B
(?=[^\W\d_])
Python demo:
import re s = "python is programming language p" print(re.sub(r'\bp(?=[^\W\d_])', '2', s, flags=re.I)) # => 2ython is 2rogramming language p print(re.sub(r'\bp\B', '2', s, flags=re.I)) # => 2ython is 2rogramming language p
你可以用
参见regex demo。你知道吗
如果您需要确保在
p
之后有一个字母,请使用见another regex demo。你知道吗
细节
\b
-单词边界p
-p
或P
(由于re.I
)\B
-非单词边界(下一个字符必须是单词字符)(?=[^\W\d_])
-一个正面的前瞻,要求任何字母立即出现在当前位置的右侧。你知道吗Python demo:
相关问题 更多 >
编程相关推荐