In Python, how to specify a format when converting int to string?

后端 未结 5 1929
终归单人心
终归单人心 2020-12-29 05:55

In Python, how do I specify a format when converting int to string?

More precisely, I want my format to add leading zeros to have a string with constant length. For

5条回答
  •  渐次进展
    2020-12-29 06:32

    With python3 format and the new 3.6 f"" notation:

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

提交回复
热议问题