76

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
34.1k10 gold badges69 silver badges107 bronze badges
asked May 16, 2012 at 17:37
2
  • 3
    string.ljust should do what you want. Can you post what you tried in the .ljust arena? Commented May 16, 2012 at 17:39
  • See also stackoverflow.com/questions/1448820/… Commented May 16, 2012 at 17:51

7 Answers 7

90

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
34.1k10 gold badges69 silver badges107 bronze badges
answered May 16, 2012 at 17:45
Sign up to request clarification or add additional context in comments.

3 Comments

See docs.python.org/library/string.html#formatspec to help with the how the format command works.
But this doesn't make it easy, because the programmer must count characters in the format string.
@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)
65

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
answered May 16, 2012 at 17:46

5 Comments

Wish I could give you more upvotes. Neat solution, didn't know about "*" operator in string formating
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?
Yes just treat it like another column: "%-9s %-20s %-9s %-20s"%("Location:","10-10-10-10", "Revision:", "1")
But if you are using python 2.6 or above use the format method by @IronMensan.
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.
52

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
34.1k10 gold badges69 silver badges107 bronze badges
answered Jul 8, 2020 at 20:17

1 Comment

IMO this is the best answer here. Exactly what I needed!
37

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
34.1k10 gold badges69 silver badges107 bronze badges
answered May 16, 2012 at 17:47

1 Comment

@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).
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'
answered May 16, 2012 at 18:26

Comments

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
answered Jul 3, 2019 at 19:48

Comments

4

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
answered Mar 30, 2022 at 7:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.