我有一个字符串,在该字符串中,我希望计数#在彼此后面出现的次数,用数字替换它们,以创建一个增量。
例如:
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
# ???发布于 2016-08-18 10:10:52
您可以在re.sub替换中使用re.sub来填充任意数量的#块。#+正则表达式模式匹配一个或多个#符号。m.group()代表正则表达式找到的匹配,因此,我们用转换为字符串填充的增量x替换所有#s,与匹配中的#数量相同。
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演示结果
MyString1_test01_edit0001
MyString1_test02_edit0002
MyString1_test03_edit0003
MyString1_test04_edit0004
MyString1_test05_edit0005发布于 2016-08-18 10:29:12
下面的代码将rawString转换为格式字符串,在列表理解中使用groupby查找散列组。每次运行散列都被转换成一个格式指令,以打印一个适当宽度的零填充整数,而非散列的运行只是简单地连接在一起。
此代码适用于Python2.6及更高版本。
from itertools import groupby
def convert(template):
return ''.join(['{{x:0{0}d}}'.format(len(list(g))) if k else ''.join(g)
for k, g in groupby(template, lambda c: c == '#')])
rawString = 'MyString1_test##_edit####'
fmt = convert(rawString)
print(repr(fmt))
for x in range(5):
print(fmt.format(x=x))输出
'MyString1_test{x:02d}_edit{x:04d}'
MyString1_test00_edit0000
MyString1_test01_edit0001
MyString1_test02_edit0002
MyString1_test03_edit0003
MyString1_test04_edit0004发布于 2016-08-18 09:59:13
这个怎么样-
rawString = 'MyString1_test##_edit####'
splitString = rawString.split('_')
for i in xrange(10): # you may put any count
print '%s_%s%02d_%s%04d' % (splitString[0], splitString[1][0:4], i, splitString[2][0:4], i, )https://stackoverflow.com/questions/39014882
复制相似问题