如何替换字符串中的第一个字母

2024-04-27 11:15:09 发布

您现在位置:Python中文网/ 问答频道 /正文

给定字符串为:

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

Tags: 方法字符串restringis字母helpit
1条回答
网友
1楼 · 发布于 2024-04-27 11:15:09

你可以用

re.sub(r'\bp\B', '2', s, flags=re.I)

参见regex demo。你知道吗

如果您需要确保在p之后有一个字母,请使用

re.sub(r'\bp(?=[^\W\d_])', '2', s, flags=re.I)

another regex demo。你知道吗

细节

  • \b-单词边界
  • p-pP(由于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

相关问题 更多 >