Python字符串:如何只替换一些数字?

2024-04-25 07:36:44 发布

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

我在用re模块练习一些正则表达式。我想知道怎么做 我们可以只更改字符串中的一些数字吗。在

a1 = 'images1/b100.png'

# required:
a2 = 'images2/b100.png'

我的尝试:

^{pr2}$

Tags: 模块字符串rea2pnga1required数字
3条回答

下面是答案

a2.replace("b200","100")

结果: 'images2/100.png'

如果你有任何问题,请告诉我。在

您可以提供一个只替换第一次出现的参数。在

更改:

a2 = a1.replace(str(num0), str(num0+1))

收件人:

^{pr2}$

如前所述:https://docs.python.org/3/library/stdtypes.html

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

您可以键入:

a2 = a1.replace(str(num0), str(num0+1), 1)

相关问题 更多 >