Python Str to Int - 非常简单但很棘手

Jes*_*dem 2 python string int string-formatting python-2.7

我的GUI应用程序中有一个小问题.只需要显示字符串.我必须执行以下逻辑.我有一个字符串'a',它们是数字.这是五位数.我必须将它增加'1'并再次将它放在我的GUI上 - 如"00002"这是代码.

a = '00001'

b = int(a) + 1

print str(b)
Run Code Online (Sandbox Code Playgroud)

预期结果:"00002" - 我得到"2"我必须为"00001"或"00043"或"00235"或"03356"或"46579"做这项工作 - 我想说 - 它必须工作对于'a'中的任意位数

Moi*_*dri 6

有多种方法可以实现它:

方法1:使用format

>>> format(2, '06d')
'000002'
Run Code Online (Sandbox Code Playgroud)

方法2:使用zfill

>>> str(2).zfill(5) 
'00002'
Run Code Online (Sandbox Code Playgroud)

方法3:使用%

>>> "%05d" % (2,)
'00002'
Run Code Online (Sandbox Code Playgroud)

选择最适合你的:)