73

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Tristan Forward
  • 3,304
  • 7
  • 35
  • 41

7 Answers7

86

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
IronMensan
  • 6,761
  • 1
  • 26
  • 35
  • 13
    See http://docs.python.org/library/string.html#formatspec to help with the how the format command works. – Charles Beattie May 16 '12 at 18:02
  • 3
    But this doesn't make it easy, because the programmer must count characters in the format string. – Arthur Sep 05 '19 at 22:18
  • @Arthur The better option is to combine them ahead of time, something like `label = 'Location'; labelled = '{0}: {1}'.format(label, Location); '{0:30}'.format(labelled)` – wjandrea Oct 02 '21 at 20:53
62

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
Charles Beattie
  • 5,739
  • 1
  • 29
  • 32
  • 5
    Wish I could give you more upvotes. Neat solution, didn't know about "*" operator in string formating – Paul Seeb May 16 '12 at 17:50
  • This is VERY close to what I am trying to do. Only thing left would be that if the District change to "DOE" that the columns would still be at the same location as before. Is there way to always set certain distance say 20 characters before the column is align that is independent of the length of value in the first column? – Tristan Forward May 16 '12 at 18:04
  • Yes just treat it like another column: `"%-9s %-20s %-9s %-20s"%("Location:","10-10-10-10", "Revision:", "1")` – Charles Beattie May 16 '12 at 18:13
  • 5
    But if you are using python 2.6 or above use the format method by @IronMensan. – Charles Beattie May 16 '12 at 18:15
  • Right, and the column width, which is `20` here, can be a Python variable of course. And if there are many rows of columns being formatted, a function or method can be written that takes the column widths and text and uses this approach to format the rows. – Arthur Oct 04 '21 at 13:44
42

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Austin U
  • 466
  • 4
  • 5
35

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
fraxel
  • 34,470
  • 11
  • 98
  • 102
  • @Frerich FYI, I had to essentially roll back your edit since it broke this answer in that the tabs weren't actually expanded. The parens need to be around the string since attribution `''.expandtabs` is more tightly binding than concatenation `'' + ''`. I think your confusion was that the code was written for Python 3 (where `print()` is a function) when actually it was for Python 2 (where `print` is a statement). – wjandrea Oct 02 '21 at 21:14
15

@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'
JoeFish
  • 3,009
  • 1
  • 18
  • 23
4

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
vshiro
  • 193
  • 1
  • 8
3

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
Udesh
  • 2,415
  • 2
  • 22
  • 32