String formatting: Columns in line
str.format()
is making your fields left aligned within the available space. Use alignment specifiers to change the alignment:
'<'
Forces the field to be left-aligned within the available space (this is the default for most objects).
'>'
Forces the field to be right-aligned within the
available space (this is the default for numbers).
'='
Forces the padding to be placed after the
sign (if any) but before the digits. This is used for printing fields
in the form ‘+000000120’. This alignment option is only valid for
numeric types.
'^'
Forces the field to be centered within the
available space.
Here's an example (with both left and right alignments):
>>> for args in (('apple', '$1.09', '80'), ('truffle', '$58.01', '2')):
... print '{0:<10} {1:>8} {2:>8}'.format(*args)
...
apple $1.09 80
truffle $58.01 2
Create nice column output in python
data = [['a', 'b', 'c'], ['String Formatting: Columns in Lineaa', '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
String Formatting: Columns in Lineaa 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 to format string output, so that columns are evenly centered?
I'm also going with the "format" suggestion, but mine is a little different.
In your program, you're relying on your card's toString
. So make that formatted in a fixed length, and then you can use them anywhere and they will take up the same space.
public String toString() {
return String.format( "%5s of %-8s", rank, suit );
}
When you print this out, you'll have all your cards aligned on the "of" part, which I think is what you were going for in your first output column.
The "%5s" part right-aligns the rank in a field 5 characters wide, and the "%-8s" part left-aligns the suit in a field 8 characters wide (which means there are additional spaces to the right if the suit is shorter than 8 characters).
columns using string formatting python
I improved my algorithm and now it works fine when the terminal size is fixed
color = {
"red": "\033[31m",
"green": "\033[32m",
"orange": "\033[33m",
"purple": "\033[35m",
"cyan": "\033[36m",
"yellow": "\033[93m",
}
def show_dirs(path=os.getcwd()):
print(color["cyan"] + "Files in the current directory")
filelist = os.listdir(path)
filelist.sort()
#index padding
ind = len(filelist)
if ind >= 1000:
ind = 4
elif ind >= 100:
ind = 3
elif ind >= 10:
ind = 2
else:
ind = 1
scr_width = int(os.get_terminal_size()[0]) #terminal width
mlen = max(len(word) for word in filelist) + 1 #column width
cols = scr_width // mlen #possible columns
if scr_width < mlen:
mlen = scr_width
line = ""
lst = []
for count, _file in enumerate(filelist, start=1):
if os.path.isdir(_file):
_file = _file + os.sep
st = "[{0:>{ind}}] {1:<{mlen}}".format(
str(count), _file, mlen=mlen, ind=ind
)
if scr_width - ((len(line) - cols * 5) % scr_width) > len(st): # - cols * 5 to compensate the length of color codes
line = line + color["cyan"] + st
else:
lst.append(line)
line = color["cyan"] + st
else:
st = "[{0:>{ind}}] {1:<{mlen}}".format(
str(count), _file, mlen=mlen, ind=ind
)
if scr_width - ((len(line) - cols * 5) % scr_width) > len(st): # - cols * 5 to compensate the length of color codes
line = line + color["green"] + st
else:
lst.append(line)
line = color["green"] + st
if lst == []:
lst.append(line)
print("\n".join(lst))
output:
Use string format create a 2D list
The syntax for padding a string with str.format()
(aligning to the left) is like this:
>>> '{:10}'.format('test')
'test '
You need to precalculate the widths of columns before printing the table. This produces the right output:
def show_table(table):
new_string = ''
widths = [max([len(col) for col in cols]) for cols in zip(*table)]
for i in table:
for j in range(len(i)):
new_string += '| {:{}} '.format(i[j], widths[j])
new_string += '|\n'
return new_string
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 a string into columns
You can specify the number of columns occupied by the text as well as alignment using Console.WriteLine
or using String.Format
:
// Prints "--123 --"
Console.WriteLine("--{0,-10}--", 123);
// Prints "-- 123--"
Console.WriteLine("--{0,10}--", 123);
The number specifies the number of columns you want to use and the sign specifies alignment (-
for left alignment, +
for right alignment). So, if you know the number of columns available, you could write for example something like this:
public string DropDownDisplay {
get {
return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
Name, City, State, ID);
}
}
If you'd like to calculate the number of columns based on the entire list (e.g. the longest name), then you'll need to get that number in advance and pass it as a parameter to your DropDownDisplay
- there is no way to do this automatically.
Related Topics
Python Requests.Get() Returns Improperly Decoded Text Instead of Utf-8
Remove a Tag Using Beautifulsoup But Keep Its Contents
Re.Sub Replace with Matched Content
Printing Utf-8 in Python 3 Using Sublime Text 3
Importerror When Importing Tkinter in Python
List Comprehension and Lambdas in Python
Get Timezone from City in Python/Django
Detecting Mouse Clicks in Windows Using Python
Log Output of Multiprocessing.Process
How to Find Duplicate Elements in Array Using for Loop in Python
How to Apply a Function on Every Row on a Dataframe
How to Initialize Weights in Pytorch
Error Running Basic Tensorflow Example
How to Simulate Jumping in Pygame for This Particular Code
How to Find First Non-Zero Value in Every Column of a Numpy Array