【发布时间】:2023-03-03 10:46:01
【问题描述】:
如何在 Python 中增加字符串?
我有以下字符串:str = 'tt0000002'
我想使用循环将此字符串增加到'tt0000003', 'tt0000004','tt0000005' (...) to 'tt0010000'。
我该怎么做?
【问题讨论】:
标签: python string for-loop while-loop
如何在 Python 中增加字符串?
我有以下字符串:str = 'tt0000002'
我想使用循环将此字符串增加到'tt0000003', 'tt0000004','tt0000005' (...) to 'tt0010000'。
我该怎么做?
【问题讨论】:
标签: python string for-loop while-loop
一种不太优雅的方式是:
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])
【讨论】:
#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
【讨论】:
你可以直接生成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'
这是一个“更智能”的版本,它应该适用于任何 'XXX0000' 形式的 id:
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'
【讨论】: