Python spacing and aligning strings

后端 未结 6 1313
失恋的感觉
失恋的感觉 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:07

    Resurrecting another topic, but this may come in handy for some.

    With a little bit of inspiration from https://pyformat.info you can build a method to get a Table of Content [TOC] style printout.

    # Define parameters
    Location = '10-10-10-10'
    Revision = 1
    District = 'Tower'
    MyDate = 'May 16, 2012'
    MyUser = 'LOD'
    MyTime = '10:15'
    
    # This is just one way to arrange the data
    data = [
        ['Location: '+Location, 'Revision:'+str(Revision)],
        ['District: '+District, 'Date: '+MyDate],
        ['User: '+MyUser,'Time: '+MyTime]
    ]
    
    # The 'Table of Content' [TOC] style print function
    def print_table_line(key,val,space_char,val_loc):
        # key:        This would be the TOC item equivalent
        # val:        This would be the TOC page number equivalent
        # space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5
        # val_loc:    This is the location in the string where the first character of val would be located
    
        val_loc = max(5,val_loc)
    
        if (val_loc <= len(key)):
            # if val_loc is within the space of key, truncate key and
            cut_str =  '{:.'+str(val_loc-4)+'}'
            key = cut_str.format(key)+'...'+space_char
    
        space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'
        print(key+space_str.format(str(val)))
    
    # Examples
    for d in data:
        print_table_line(d[0],d[1],' ',30)
    
    print('\n')
    for d in data:
        print_table_line(d[0],d[1],'_',25)
    
    print('\n')
    for d in data:
        print_table_line(d[0],d[1],' ',20)
    

    The resulting output is as follows:

    Location: 10-10-10-10         Revision:1
    District: Tower               Date: May 16, 2012
    User: LOD                     Time: 10:15
    
    
    Location: 10-10-10-10____Revision:1
    District: Tower__________Date: May 16, 2012
    User: LOD________________Time: 10:15
    
    
    Location: 10-10-... Revision:1
    District: Tower     Date: May 16, 2012
    User: LOD           Time: 10:15
    
    0 讨论(0)
  • 2020-12-04 09:12

    As of Python 3.6, we have a better option, f-strings!

    >>> print(f"{'Location: ' + location:<25} Revision: {revision}")
    >>> print(f"{'District: ' + district:<25} Date: {date}")
    >>> print(f"{'User: ' + user:<25} Time: {time}")
    

    Output:

    Location: 10-10-10-10     Revision: 1
    District: Tower           Date: May 16, 2012
    User: LOD                 Time: 10:15
    

    Since everything within the curly brackets is evaluated at runtime, we can enter both the string 'Location: ' concatenated with the variable location. Using :<25 places the entire concatenated string into a box 25 characters long, and the < designates that you want it left aligned. That way, the second column always starts after those 25 characters reserved for the first column.

    Another benefit here is that you don't have to count the characters in your format string. Using 25 will work for all of them, provided that 25 is long enough to contain all of the characters in your left column.

    https://realpython.com/python-f-strings/ explains the benefits of f-strings over previous options. https://medium.com/@NirantK/best-of-python3-6-f-strings-41f9154983e explains how to use <, >, and ^ for left, right, and center aligned.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-04 09:18

    You can use expandtabs to specify the tabstop, like this:

    >>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
    >>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
    #Output:
    Location:10-10-10-10          Revision: 1
    District: Tower               Date: May 16, 2012
    
    0 讨论(0)
  • 2020-12-04 09:25

    You should be able to use the format method:

    "Location: {0:20} Revision {1}".format(Location,Revision)
    

    You will have to figure out the of the format length for each line depending on the length of the label. The User line will need a wider format width than the Location or District lines.

    0 讨论(0)
  • 2020-12-04 09:25

    Try %*s and %-*s and prefix each string with the column width:

    >>> print "Location: %-*s  Revision: %s" % (20,"10-10-10-10","1")
    Location: 10-10-10-10           Revision: 1
    >>> print "District: %-*s  Date: %s" % (20,"Tower","May 16, 2012")
    District: Tower                 Date: May 16, 2012
    
    0 讨论(0)
提交回复
热议问题