代码之家  ›  专栏  ›  技术社区  ›  pierroz

在Python中,如何在将int转换为字符串时指定格式?

  •  12
  • pierroz  · 技术社区  · 15 年前

    在Python中,如何在将int转换为字符串时指定格式?

    更准确地说,我希望我的格式添加前导零,使其具有字符串 长度不变。例如,如果常量长度设置为4:

    • 1将转换为“0001”
    • 12将转换为“0012”
    • 165将转换为“0165”

    当整数大于允许的给定长度(在我的示例中是9999)时,我对行为没有约束。

    我怎么能在 Python ?

    5 回复  |  直到 8 年前
        1
  •  14
  •   nmichaels    15 年前

    "%04d" 其中4是常量长度,将执行您所描述的操作。

    您可以阅读字符串格式 here.

        2
  •  12
  •   Srikar Appalaraju Tonetel    10 年前

    你可以使用 zfill 功能 str 类。就像这样-

    >>> str(165).zfill(4)
    '0165'
    

    一个人也可以 %04d 像其他人建议的那样。但我认为这是一种更像蟒蛇的方式…

        3
  •  4
  •   Powertieke    15 年前

    尝试 formatted string printing :

    print "%04d" % 1 输出0001

        4
  •  3
  •   BitOfAByte mac    10 年前

    使用百分比( % )操作员:

    >>> number = 1
    >>> print("%04d") % number
    0001
    >>> number = 342
    >>> print("%04d") % number
    0342
    

    文件是 over here

    使用的优势 % 与zfill()不同的是,您可以更清晰地将值解析为字符串:

    >>> number = 99
    >>> print("My number is %04d to which I can add 1 and get %04d") % (number, number+1)
    My number is 0099 to which I can add 1 and get 0100
    
        5
  •  3
  •   MortenB    8 年前

    使用python3格式符号:

    >>> i = 5
    >>> "{:4n}".format(i)
    '   5'
    >>> "{:04n}".format(i)
    '0005'