Python spacing and aligning strings

Each Answer to this Q is separated by one/two green lines.

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 column being aligned.

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

Currently have it coded like this, just using spaces…

"Location: " + Location + "               Revision: " + Revision + '\n'

I tried working with string.rjust & srting.ljust but to no avail.

Suggestions?

You should be able to use the format method:

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

You will have to figure out 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.

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

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

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.

@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'

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

Python f-string

Python f-string is the newest Python syntax to do string formatting.
It is available since Python 3.6. Python f-strings provide a faster,
more readable, more concise, and less error prone way of formatting
strings in Python.

Please visit here for elaborate discussion regarding string formatting.

Source:

#!/usr/bin/env python3

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

from datetime import datetime

location = "10-10-10-10"
revision = 1
district = "Tower"
now = datetime.now()
user = "LOD"


width = 30#the width of string

loc = f"Location: {location}"
print(f"{loc: <{width}} Revision: {revision}")

dist = f"District: {district}"
print(f"{dist : <{width}} Date: {now :%b %d, %Y}")

usr = f"User: {user}"
print(f"{usr : <{width}} Time: {now :%H:%M}")

Output:

Location: 10-10-10-10          Revision: 1
District: Tower                Date: Mar 30, 2022
User: LOD                      Time: 12:29


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .