如何将Python 3中的数字格式化为字符串?

时间:2014-08-26 08:57:50

标签: python python-3.x string-formatting

我想用Python 3将数字(int,float)转换为字符串。如果我按字母顺序对字符串进行排序,结果也应该在数字上正确。这是愿望清单:

  • 1 => "001"
  • 10 => "010"
  • 100 => "100"
  • 5.6 => "005.6"

我可以确保数字小于1000.如果有帮助,我也可以保证小数点后最多只有一位数。

我可以编写一个执行此操作的函数。但这也可以用.format()魔法来实现吗?

3 个答案:

答案 0 :(得分:1)

你也可以打开type intead,例如:

for i in (1, 10, 100, 5.6): 
    print(format(i, {float: '05.1f', int: '03'}[type(i)]))

结果:

001
010
100
005.6

答案 1 :(得分:0)

如果您需要处理浮点数,那么在首先对小数值进行分区后,最好使用str.zfill() method

def pad_number(num):
    num = str(num).partition('.')
    return ''.join((num[0].zfill(3),) + num[1:])

这里str.partition()给出了一个包含3个元素的元组,如果没有小数点,则后两个元素为空。这使我们有机会只填充数字的整数部分。

如果您不需要处理浮点值,那么format()将是一个很好的工具:

format(intnum, '03d')

但是它会截断浮点值,对于浮点数,你必须使用不同的格式字符串,该字符串随你需要包含的小数位数而变化。

演示:

>>> def pad_number(num):
...     num = str(num).partition('.')
...     return ''.join((num[0].zfill(3),) + num[1:])
... 
>>> for i in (1, 10, 100, 5.6):
...     print(pad_number(i))
... 
001
010
100
005.6

答案 2 :(得分:0)

from math import trunc
from math import log10

def pad_number_sequence(seq, prec=1):
    """Convert a sequence of numbers to a list of zero-padded strings.

    The number of decimals in the converted floats is controlled by prec.

    Depending on the size of the numbers in the sequence the width
    will be dynamically calculated so that the resulting string
    representation will align.
    """
    digits_left_of_decimal = trunc(log10(max(abs(x) for x in seq))) + 1
    width = digits_left_of_decimal + prec + 2  # 1 decimal point, 1 sign
    num2str = { float: "{number:0= {width}.{prec}f}",
                int: "{number:0= {width}}", }
    return [num2str[type(n)].format(number=n, prec=prec, width=width) 
            for n in seq]


# Example use.
lnum = [0, 1, 3.1415, -3.1415, 10, 100, -1, 999.9, 234.32, -98.99, -999.9, -999.9]
print('Aligned numbers:')
for s in pad_number_sequence(lnum):
    print(s)

# Sorting is best done by adding a sorting key.
print(sorted(pad_number_sequence(lnum), key=lambda x: float(x)))

运行它将产生输出:

Aligned numbers:
 00000
 00001
 003.1
-003.1
 00010
 00100
-00001
 999.9
 234.3
-099.0
-999.9
-999.9
['-999.9', '-999.9', '-099.0', '-003.1', '-00001', ' 00000', ' 00001', ' 003.1', ' 00010', ' 00100', ' 234.3', ' 999.9']