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 do I right align my string? in python
you can format your string to be padded and aligned inside an f-string. In this case i use the >
to donate right aligned and use the value of longest
to tell it how much to pad/align it by
strings = ['abc', 'de', 'fghijklmn']
longest = len(max(strings, key=len))
print("\n".join([f"{string: >{longest}}" for string in strings]))
OUTPUT
abc
de
fghijklmn
C how do I right align string and float
Get rid of the minus in your format statement.
%<width>s
example:
#include <stdio.h>
int main()
{
printf("%15s %5d %5.2f 0x%08X\n", "hello", 42, 3.14, 0xDEAD);
return 0;
}
output:
Chris@DESKTOP-BCMC1RF ~
$ ./main.exe
hello 42 3.14 0x0000DEAD
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 the
ValueError: Single
'}'
encountered in format string
comes from.
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
How to right align the output according to the length of the largest word in a list in python 3.xx
Option 1
Pre-compute the length of the largest string and pass it as a separate parameter to format
.
l = len(max(a, key=len))
for i in a:
print("{n:>{w}}".format(n=i, w=l))
bicycle
airplane
car
boat
Option 2
An alternative using str.rjust
:
for i in a:
print(i.rjust(l)) # same `l` as computed in Option 1
bicycle
airplane
car
boat
Option 3
You can also print a dump of pd.Series.to_string
:
import pandas as pd
print(pd.Series(a).to_string())
0 bicycle
1 airplane
2 car
3 boat
Other tabulation packages (I use tabulate
) can also be used to good effect here.
Align text to right in C
You can use printf("%*s", <width>, "a");
to print any text right aligned by variable no. of spaces.
Check here live.
Right Justify python
You can use format
with >
to right justify
N = 10
for i in range(1, N+1):
print('{:>10}'.format('#'*i))
Output
#
##
###
####
#####
######
#######
########
#########
##########
You can programattically figure out how far to right-justify using rjust
as well.
for i in range(1, N+1):
print(('#'*i).rjust(N))
How to right align with positive symbol and comma separator in Python print?
From the format string documentation, you should have the sign goes after the alignment. In this case, you should change the format string from
"{:<8} {:+>10,}"
to
"{:<8} {:>+10,}"
Related Topics
Automatically Create Requirements.Txt
Compare Two Dataframes and Output Their Differences Side-By-Side
Python Setup.Py Develop VS Install
What Is the Purpose of Class Methods
Passing Functions with Arguments to Another Function in Python
Explaining the 'Self' Variable to a Beginner
Detecting Consecutive Integers in a List
Removing Duplicate Characters from a String
Python, Typeerror: Unhashable Type: 'List'
Check If a String Matches an Ip Address Pattern in Python
Sftp in Python? (Platform Independent)
Pandas Dataframe Get First Row of Each Group
How to Read First N Lines of a File
How to Remove Stop Words Using Nltk or Python
Is There a Decorator to Simply Cache Function Return Values
How to Access "Static" Class Variables Within Methods in Python