Setting fixed length with python

前端 未结 5 1219
遇见更好的自我
遇见更好的自我 2021-01-05 02:19

I have str that are like \'60\' or \'100\'. I need the str to be \'00060\' and \'00100\',

How can i do this? code is something like this: I was using \'0\'+\'0\'+

相关标签:
5条回答
  • 2021-01-05 02:26

    Reading your favorite Python documentation appreciated:

    http://docs.python.org/library/string.html#formatstrings

    """

    If the width field is preceded by a zero ('0') character, this enables zero-padding. This is equivalent to an alignment type of '=' and a fill character of '0'. """

    0 讨论(0)
  • 2021-01-05 02:31

    If it's already a string you might want to use the .zfill() method.

    myval.fill(5)
    
    0 讨论(0)
  • 2021-01-05 02:34

    If "60" is already a string, you have to convert it to a number before applying the formatting. The most practical one works just like C's printf:

    a  ="60"
    b = "%05d" % int(a)
    
    0 讨论(0)
  • 2021-01-05 02:35

    Since you are manipulating strings, str.zfill() does exactly what you want.

    >>> s1, s2 = '60', '100'
    >>> print s1.zfill(5), s2.zfill(5)
    00060 00100
    
    0 讨论(0)
  • 2021-01-05 02:38

    Like this:

    num = 60 
    formatted_num = u'%05d' % num
    

    See the docs for more information about formatting numbers as strings.

    If your number is already a string (as your updated question indicates), you can pad it with zeros to the right width using the rjust string method:

    num = u'60'
    formatted_num = num.rjust(5, u'0')
    
    0 讨论(0)
提交回复
热议问题