gpt4 book ai didi

Python:计算字符串中相互跟随的字符

转载 作者:太空宇宙 更新时间:2023-11-03 16:14:59 25 4
gpt4 key购买 nike

我有一个字符串,我想在其中计算 # 的出现次数,并用数字替换它们以创建增量。

例如:

rawString = 'MyString1_test##_edit####'

for x in xrange(5):
output = doConvertMyString(rawString)
print output

MyString1_test01_edit0001
MyString1_test02_edit0002
MyString1_test03_edit0003
MyString1_test04_edit0004
MyString1_test05_edit0005

假设#的个数不固定,且rawString是仅包含string.ascii_letters + string.digits + '_' +的用户输入'#,我该怎么做?

这是我迄今为止的测试:

rawString = 'MyString1_test##_edit####'
incrDatas = {}
key = '#'
counter = 1

for x in xrange(len(rawString)):
if rawString[x] != key:
counter = 1
continue
else:
if x > 0:
if rawString[x - 1] == key:
counter += 1
else:
pass
# ???

最佳答案

您可以在 re.sub 替换中使用 zfill 来填充任意数量的 # block 。 #+ 正则表达式模式匹配 1 个或多个 # 符号。 m.group() 代表正则表达式找到的匹配项,因此,我们用转换为字符串的递增的 x 替换所有 #使用与匹配中的 # 相同数量的 0 进行填充。

import re
rawString = 'MyString1_test##_edit####'
for x in xrange(5):
output = re.sub(r"#+", lambda m: str(x+1).zfill(len(m.group())), rawString)
print output

the demo 的结果:

MyString1_test01_edit0001
MyString1_test02_edit0002
MyString1_test03_edit0003
MyString1_test04_edit0004
MyString1_test05_edit0005

关于Python:计算字符串中相互跟随的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39014882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com