Python 字符串格式化:填充负数 [英] Python string formatting: padding negative numbers
问题描述
我想将我的整数格式化为字符串,以便在没有符号的情况下,它们将被零填充以至少包含两位数字.
I would like to format my integers as strings so that, without the sign, they will be zero-padded to have at least two digits.
例如我想要
1
-1
10
-10
成为
01
-01
10
-10
具体来说,我希望负数 (3) 和非负数 (2) 的最小字符串长度不同.此处 中的简单数字填充是不够的.这可能吗?
Specifically, I want different minimum string lengths for negative numbers (3) and non-negative numbers (2). Simple number padding as detailed here is insufficient. Is this possible?
推荐答案
您可以使用 str.format
,但在大小上加 1 以将负数考虑在内:
you could use str.format
, but adding 1 to the size to take the negative number into account here:
l = [1,-1,10,-10,4]
new_l = ["{1:0{0}d}".format(2 if x>=0 else 3,x) for x in l]
print(new_l)
结果:
['01', '-01', '10', '-10', '04']
之所以有效,是因为 format
接受嵌套表达式:您可以将大小 ({:02d}
或 {:03d}
) 作为格式项也省去了第一遍格式化格式字符串的麻烦.
it works because format
accepts nested expressions: you can pass the size ({:02d}
or {:03d}
) as a format item too when saves the hassle of formatting the format string in a first pass.
这篇关于Python 字符串格式化:填充负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!