如何在Python中增加字符串值



如何在Python中增加字符串?

我有以下字符串:str = 'tt0000002'并且我想使用循环将这个字符串增加到'tt0000003', 'tt0000004','tt0000005' (...) to 'tt0010000'

我该怎么做呢?

您可以直接生成id:

的例子,值在2到100之间,增量为10:

ids = [f'tt{i:07d}' for i in range(2, 100, 10)]

输出:

['tt0000002',
'tt0000012',
'tt0000022',
'tt0000032',
'tt0000042',
'tt0000052',
'tt0000062',
'tt0000072',
'tt0000082',
'tt0000092']

如果你真的需要从你的字符串中增加:

def increment(s):
# splitting here after 2 characters, but this could use a regex
# or any other method if the identifier is more complex
return f'{s[:2]}{int(s[2:])+1:07d}'

的例子:

>>> mystr = 'tt0000002'
>>> increment(mystr)
'tt0000003'

编辑

这里有一个"smarter"应该与任何id为'XXX0000'的表单一起工作的版本:

def increment(s):
import re
try:
a, b = re.match('(D*)(d+)', s).groups()
except (AttributeError, IndexError):
print('invalid id')
return 
return f'{a}{int(b)+1:0{len(b)}d}'

例子:

>>> increment('tt0000002')
'tt0000003'
>>> increment('abc1')
'abc2'
>>> increment('abc999')
'abc1000'
>>> increment('0000001')
'0000002'
#ugly code but works
s='tt0000002'
for k in range(100): #increase the range 
print(s)
n=int(s[2:])
n_s=str(n+1)
l=len(n_s)
temp='tt'
for z in range(0,7-l):
temp+='0'
s=temp+n_s

一种不那么优雅的方式是:

def increment_string(string, num_chars, numbers):
return [f'{string}{str(0) * (num_chars-len(str(i)))}' + str(i) for i in numbers]

increment_string(string = 'tt', num_chars = 8, numbers = [1,10,50,100,1000,100000,1000000,1000000,10000000])

最新更新