How to set the spaces in a string format in Python 3

时间秒杀一切 提交于 2019-12-10 17:33:23

问题


How can I set up the string format so that I could use a variable to ensure the length can change as needed? For example, lets say the length was 10 at first, then the input changes then length becomes 15. How would I get the format string to update?

    length =  0
    for i in self.rows:
        for j in i:
            if len(j) > length:
                length  = len(j)
    print('% length s')

Obviously the syntax above is wrong but I can't figure out how to get this to work.


回答1:


Using str.format

>>> length = 20
>>> string = "some string"
>>> print('{1:>{0}}'.format(length, string))
         some string



回答2:


You can use %*s and pass in length as another parameter:

>>> length = 20
>>> string = "some string"
>>> print("%*s" % (length, string))
         some string

Or use a format string to create the format string:

>>> print(("%%%ds" % length) % string)
         some string



回答3:


The format method allows nice keyword arguments combined with positional arguments:

>>> s = 'my string'
>>> length = 20
>>> '{:>{length}s}'.format(s, length=length)
'           my string'



回答4:


You can declare like this:

 print('%20s'%'stuff')

20 would be the number of characters in the print string. The excess in whitespace.



来源:https://stackoverflow.com/questions/36138895/how-to-set-the-spaces-in-a-string-format-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!