Python spacing and aligning strings
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. Python: String Formatter Align center
Use the new-style format
method instead of the old-style %
operator, which doesn't have the centering functionality:
print('{:^24s}'.format("MyString"))
Format output string, right alignment
Try this approach using the newer str.format
syntax:
line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2])
And here's how to do it using the old %
syntax (useful for older versions of Python that don't support str.format
):line_new = '%12s %12s %12s' % (word[0], word[1], word[2])
How to set a variable space with right alignment for a string in Python?
Your problem is operator order - the +
for string concattenation is weaker then the method call in
'{:>' + str(space) + 's}'.format(str(bin(i))[2:])
. Thats why you call the .format(...)
only on "s}"
- not the whole string. And thats where thecomes from.ValueError: Single
'}'
encountered in format string
Putting the complete formatstring into parenthesis before applying .format
to it fixes that.
You also need 1 more space for binary and can skip some str()
that are not needed:
def print_formatted(number):
space=len(str(bin(number))[2:])+1 # fix here
for i in range(1,number+1):
print('{:2d}'.format(i), end='')
print('{:>3s}'.format(oct(i)[2:]), end='')
print('{:>3s}'.format(hex(i)[2:]), end='')
print(('{:>'+str(space)+'s}').format(bin(i)[2:])) # fix here
print_formatted(17)
Output: 1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 a 1010
11 13 b 1011
12 14 c 1100
13 15 d 1101
14 16 e 1110
15 17 f 1111
16 20 10 10000
17 21 11 10001
From your given output above you might need to prepend this by 2 spaces - not sure if its a formatting error in your output above or part of the restrictions.
You could also shorten this by using f-strings (and removing superflous
str()
around bin, oct, hex
: they all return a strings already).Then you need to calculate the the numbers you use to your space out your input values:
def print_formatted(number):
de,bi,oc,he = len(str(number)), len(bin(number)), len(oct(number)), len(hex(number))
for i in range(1,number+1):
print(f' {i:{de}d}{oct(i)[2:]:>{oc}s}{hex(i)[2:]:>{he}s}{bin(i)[2:]:>{bi}s}')
print_formatted(26)
to accomodate other values then 17, f.e. 128: 1 1 1 1
2 2 2 10
3 3 3 11
...
8 10 8 1000
...
16 20 10 10000
...
32 40 20 100000
...
64 100 40 1000000
...
128 200 80 10000000
String alignment when printing in python
Probably, the most elegant way is to use the format
method. It allows to easily define the space a string will use:
>>> name = 'Якета'
>>> asterisks = '****************************'
>>> price = 1250.23
>>> print '{0:17}: {1} {2} €'.format(name, asterisks, price)
Якета : **************************** 1250.23 €
Should you need to programmatically define padding size (for instance, to dynamically accept larger strings instead of hard-coding its size), simply use ljust
:>>> name = 'Якета'
>>> asterisks = '****************************'
>>> price = 1250.23
>>> padding = 17
>>> print '{0}: {1} {2} €'.format(name.ljust(padding), asterisks, price)
Якета : **************************** 1250.23 €
Considering the case when the maximum string size is unknown previously and the script must adapt to it, we only need to calculate the maximum string size and place it in padding
:>>> names = ['abc', 'defghijklm', 'op', 'q']
>>> asterisks = '****************************'
>>> price = 1250.23
>>> padding = max(map(len, strings))
>>> for name in names:
print '{0}: {1} {2} €'.format(name.ljust(padding), asterisks, price)
abc : **************************** 1250.23 €
defghijklm: **************************** 1250.23 €
op : **************************** 1250.23 €
q : **************************** 1250.23 €
This thread has a pretty similar issue. Python Padding strings to align columns in a Tkinter ListBox widget
If what you want to do is to align two columns of strings in a single listbox, I would suggest the following:
Use tkFont to measure the lengths of the left strings (for the exact font used) as described here
Add spaces between left and right strings so that the right string always start at the same position (in practice this position will vary by a few pixels because even the "space" character is a few pixels wide)
Code (Python 2.x)
import Tkinter as Tk
import tkFont
#Create a listbox
master = Tk.Tk()
listbox = Tk.Listbox(master, width=40, height=20)
listbox.pack()
# Dummy strings to align
stringsLeft = ["short", "medium", "extra-------long", "short", "medium", "short"]
stringsRight = ["one", "two", "three", "four", "five", "six"]
# Get the listbox font
listFont = tkFont.Font(font=listbox.cget("font"))
# Define spacing between left and right strings in terms of single "space" length
spaceLength = listFont.measure(" ")
spacing = 12 * spaceLength
# find longest string in the left strings
leftLengths = [listFont.measure(s) for s in stringsLeft]
longestLength = max(leftLengths)
# combine left and righ strings with the right number of spaces in between
for i in range(len(stringsLeft)):
neededSpacing = longestLength + spacing - leftLengths[i]
spacesToAdd = int(round(neededSpacing/spaceLength))
listbox.insert(Tk.END, stringsLeft[i] + spacesToAdd * " " + stringsRight[i])
Tk.mainloop()
For Python 3.x, replace the import statements with:import tkinter as Tk
from tkinter import font as tkFont
Create nice column output in python
data = [['a', 'b', 'c'], ['Python Spacing and Aligning Stringsaa', 'b', 'c'], ['a', 'bb', 'c']]
col_width = max(len(word) for row in data for word in row) + 2 # padding
for row in data:
print "".join(word.ljust(col_width) for word in row)
a b c
Python Spacing and Aligning Stringsaa b c
a bb c
What this does is calculate the longest data entry to determine the column width, then use .ljust()
to add the necessary padding when printing out each column. How can I fill out a Python string with spaces?
You can do this with str.ljust(width[, fillchar])
:
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than
len(s)
.
>>> 'hi'.ljust(10)
'hi '
Related Topics
How to Create Module-Wide Variables in Python
Multiprocessing:Use Tqdm to Display a Progress Bar
Python Progress Bar and Downloads
Is There a Simple Process-Based Parallel Map for Python
Regex for Existence of Some Words Whose Order Doesn't Matter
How to Skip Iterations in a Loop
Count the Number of Occurrences of a Certain Value in a Dictionary in Python
What Is the Official "Preferred" Way to Install Pip and Virtualenv Systemwide
How to Explain the Reverse of a Sequence by Slice Notation A[::-1]
Wrapping Long Y Labels in Matplotlib Tight Layout Using Setp
How to Troubleshoot Python "Could Not Find Platform Independent Libraries <Prefix>"
Numpy Argsort - What Is It Doing
How to Plot Empirical Cdf (Ecdf)
How to Flatten a Pandas Dataframe with Some Columns as JSON
Join Two Lists of Dictionaries on a Single Key