Mar*_*icz -2 python string for-loop while-loop
如何在Python中增加字符串的值?
我有以下字符串:str = 'tt0000002'
并且我想增加该字符串以'tt0000003', 'tt0000004','tt0000005' (...) to 'tt0010000'使用循环。
我怎样才能做到这一点?
您可以直接生成 ids:
此处的示例值介于 2 到 100 之间,增量为 10:
ids = [f'tt{i:07d}' for i in range(2, 100, 10)]
Run Code Online (Sandbox Code Playgroud)
输出:
['tt0000002',
'tt0000012',
'tt0000022',
'tt0000032',
'tt0000042',
'tt0000052',
'tt0000062',
'tt0000072',
'tt0000082',
'tt0000092']
Run Code Online (Sandbox Code Playgroud)
如果您确实需要从字符串中增加:
['tt0000002',
'tt0000012',
'tt0000022',
'tt0000032',
'tt0000042',
'tt0000052',
'tt0000062',
'tt0000072',
'tt0000082',
'tt0000092']
Run Code Online (Sandbox Code Playgroud)
例子:
>>> mystr = 'tt0000002'
>>> increment(mystr)
'tt0000003'
Run Code Online (Sandbox Code Playgroud)
这是一个“更智能”的版本,应该适用于“XXX0000”形式的任何 id:
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}'
Run Code Online (Sandbox Code Playgroud)
例子:
>>> increment('tt0000002')
'tt0000003'
>>> increment('abc1')
'abc2'
>>> increment('abc999')
'abc1000'
>>> increment('0000001')
'0000002'
Run Code Online (Sandbox Code Playgroud)