Python spacing and aligning strings

后端 未结 6 1329
失恋的感觉
失恋的感觉 2020-12-04 08:42

I am trying to add spacing to align text in between two strings vars without using \" \" to do so

Trying to get the text to look like this, with the second co

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 09:17

    @IronMensan's format method answer is the way to go. But in the interest of answering your question about ljust:

    >>> def printit():
    ...     print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
    ...     print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
    ...     print 'User: LOD'.ljust(40) + 'Time: 10:15'
    ...
    >>> printit()
    Location: 10-10-10-10                   Revision: 1
    District: Tower                         Date: May 16, 2012
    User: LOD                               Time: 10:15
    

    Edit to note this method doesn't require you to know how long your strings are. .format() may also, but I'm not familiar enough with it to say.

    >>> uname='LOD'
    >>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
    'User: LOD                               Time: 10:15'
    >>> uname='Tiddlywinks'
    >>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
    'User: Tiddlywinks                       Time: 10:15'
    

提交回复
热议问题