[python] Python spacing and aligning strings

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?

This question is related to python string alignment

The answer is


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

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to alignment

How do I center text vertically and horizontally in Flutter? CSS align one item right with flexbox What's the difference between align-content and align-items? align images side by side in html How to align iframe always in the center How to make popup look at the centre of the screen? Responsive image align center bootstrap 3 How to align title at center of ActionBar in default theme(Theme.Holo.Light) Center align a column in twitter bootstrap How do I position an image at the bottom of div?