简体   繁体   English

Python 3.4字符串操作-截断前导零

[英]python 3.4 string manipulation - truncating leading zeros

There are a number of existing posts on this topic, but I cannot get this simple piece of code to work correctly. 关于此主题的现有文章很多,但我无法使这段简单的代码正常工作。 I have tried many many times with no success... 我尝试了很多次都没有成功...

per = 5


if per < 10 == True:
    ms = 'fwd_%sd' % str(per).zfill(2)
else:
    ms = 'fwd_%sd' % per

and

if per < 10 == True:
    a = format(per, 'fwd_02d')
else:
    a = 'fwd_%sd' % per

The result should be 'fwd_05d' but I can only get 'fwd_5d'. 结果应该是“ fwd_05d”,但我只能得到“ fwd_5d”。

Among others, I have seen: 除其他外,我已经看到:

Display number with leading zeros 显示数字的前导零

Add leading zero python 添加前导零python

Please help! 请帮忙!

You can use str.format, if you are actually doing nothing else but padding just use ms = 'fwd_{:02}d'.format(per) and forget the if/else, only numbers less than 10 will be padded with a 0. The 0 in {:02} is what to pad with and the 2 is the size to pad to. 您可以使用str.format,如果实际上除了填充以外什么也没做,则只需使用ms = 'fwd_{:02}d'.format(per)ms = 'fwd_{:02}d'.format(per) if / else,只有小于10的数字会被填充0。 {:02}的0是要填充的内容,而2是要填充的大小。

ms = 'fwd_{:02}d'.format(per)

On another note if per < 10 == True: is the same as if per < 10: 另外请注意, if per < 10 == True:if per < 10:相同if per < 10:

You can just create a temp str variable, check if less than 10, and add a zero to the front if needed. 您可以只创建一个temp str变量,检查是否小于10,并在需要时在前面添加一个零。 Also, you shouldn't have an if statement and then check if it equals true. 另外,您不应该具有if语句,然后检查它是否等于true。 It is redundant and makes your code less readable. 它是多余的,使您的代码可读性较低。

per = 5

if per < 10:
    perStr = '0' + str(per)

print('fwd_' + perStr + 'd')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM