Using the f-string format becomes very easy nowadays.
If you were using
print(f'{token:10}')
And you want the 10 to be another variable (for example the max length of all the tokens), you would write
print(f'{token:{maxTokenLength}}')
In other words, enclose the variable within {}
In your particular case, all you need is this.
head = 'eggs', 'bacon', 'spam'
w1, w2, w3 = 8, 7, 10 # column widths
print(f' {head[0]:>{w1}} {head[1]:>{w2}} {head[2]:>{w3}}')
print(f' {"="*w1:>{w1}} {"="*w2:>{w2}} {"="*w3:>{w3}}')
Which produces
eggs bacon spam
======== ======= ==========
Answer from Rub on Stack OverflowUsing the f-string format becomes very easy nowadays.
If you were using
print(f'{token:10}')
And you want the 10 to be another variable (for example the max length of all the tokens), you would write
print(f'{token:{maxTokenLength}}')
In other words, enclose the variable within {}
In your particular case, all you need is this.
head = 'eggs', 'bacon', 'spam'
w1, w2, w3 = 8, 7, 10 # column widths
print(f' {head[0]:>{w1}} {head[1]:>{w2}} {head[2]:>{w3}}')
print(f' {"="*w1:>{w1}} {"="*w2:>{w2}} {"="*w3:>{w3}}')
Which produces
eggs bacon spam
======== ======= ==========
Specifying w[0], w[1], w[2] should work if you defined w = 8, 7, 10 and passed w as keyword argument like below:
>>> head = 'eggs', 'bacon', 'spam'
>>> w = 8, 7, 10 # <--- list is also okay
>>> line = ' {:{ul}>{w[0]}} {:{ul}>{w[1]}} {:{ul}>{w[2]}}'
>>> under = 3 * '='
>>> print line.format(*head, ul='', w=w) # <-- pass as a keyword argument
eggs bacon spam
>>> print line.format(*under, ul='=', w=w) # <-- pass as a keyword argument
======== ======= ==========
python 3.x - encode ,length of character and width of display in python3 - Stack Overflow
python 3.x - Width of character - Stack Overflow
Width of a string with zero-width and two-width characters, in Python 3 in a terminal (not in a GUI) - Stack Overflow
string - Fixed width number formatting python 3 - Stack Overflow
I find using str.format much more elegant:
>>> '{0: <5}'.format('s')
's '
>>> '{0: <5}'.format('ss')
'ss '
>>> '{0: <5}'.format('sss')
'sss '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'
In case you want to align the string to the right use > instead of <:
>>> '{0: >5}'.format('ss')
' ss'
Edit 1:
As mentioned in the comments: the 0 in '{0: <5}' indicates the argument’s index passed to str.format().
Edit 2: In python3 one could use also f-strings:
sub_str='s'
for i in range(1,6):
s = sub_str*i
print(f'{s:>5}')
' s'
' ss'
' sss'
' ssss'
'sssss'
or:
for i in range(1,5):
s = sub_str*i
print(f'{s:<5}')
's '
'ss '
'sss '
'ssss '
'sssss'
of note, in some places above, ' ' (single quotation marks) were added to emphasize the width of the printed strings.
EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.
You can use string formatting like this:
>>> print '%5s' % 'aa'
aa
>>> print '%5s' % 'aaa'
aaa
>>> print '%5s' % 'aaaa'
aaaa
>>> print '%5s' % 'aaaaa'
aaaaa
Basically:
- the
%character informs python it will have to substitute something to a token - the
scharacter informs python the token will be a string - the
5(or whatever number you wish) informs python to pad the string with spaces up to 5 characters.
In your specific case a possible implementation could look like:
>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
... print 'value %3s - num of occurances = %d' % item # %d is the token of integers
...
value a - num of occurances = 1
value ab - num of occurances = 1
value abc - num of occurances = 1
SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:
>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']
and you could get the number of occurrences by using combinations in conjunction with count().
Hello friends,
Today I got stuck on a formatting issue and decided to learn more about the applications of width and precision with string Formatting of floats, integers and strings.
I have put down my learnings in an article and would like to share with you. Do share if there are other intricacies that I have missed!
Not sure why it is in the module shutil, but it landed there in Python 3.3. See:
Querying the size of the output terminal
>>> import shutil
>>> shutil.get_terminal_size((80, 20)) # pass fallback
os.terminal_size(columns=87, lines=23) # returns a named-tuple
A low-level implementation is in the os module. Cross-platform—works under Linux, Mac OS, and Windows, probably other Unix-likes. There's a backport as well, though no longer relevant.
import os
rows, columns = os.popen('stty size', 'r').read().split()
uses the 'stty size' command which according to a thread on the python mailing list is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from it, and uses a simple string split to separate the coordinates.
Unlike the os.environ["COLUMNS"] value (which I can't access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ["COLUMNS"] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).
(See answer by @GringoSuave on how to do this on python 3.3+)