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
======== ======= ==========
string - How do I format a number with a variable number of digits in Python? - Stack Overflow
format - Python f-string with variable width alignment and variable text - Stack Overflow
python - Format string dynamically - Stack Overflow
python - How to use variables for width and precision in str.format()? - Stack Overflow
If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting
>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings
Here is an example with variable width
>>> '{num:0{width}}'.format(num=123, width=6)
'000123'
You can even specify the fill char as a variable
>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
There is a string method called zfill:
>>> '12344'.zfill(10)
0000012344
It will pad the left side of the string with zeros to make the string length N (10 in this case).
In this statement print(f"|{students[i+j]:^{CELL_WIDTH}}", end='') the data type of variable CELL_WIDTH is float which is supposed to be int ..
Change the statement CELL_WIDTH = (LINE_WIDTH - STUDENTS_PER_ROW - 1) / STUDENTS_PER_ROW with CELL_WIDTH = (LINE_WIDTH - STUDENTS_PER_ROW - 1) // STUDENTS_PER_ROW which will make CELL_WIDTH datatype as int..
I think you'd need to add int() to your statement because CELL_WIDTH is a float value.
So:
CELL_WIDTH=int(LINE_WIDTH - STUDENTS_PER_ROW-1)/STUDENTS_PER_ROW
Hope that helps!
You can do this using the str.format() method.
>>> width = 20
>>> print("{:>{width}} : {:>{width}}".format("Python", "Very Good", width=width))
Python : Very Good
Starting from Python 3.6 you can use f-string to do this:
In [579]: lang = 'Python'
In [580]: adj = 'Very Good'
In [581]: width = 20
In [582]: f'{lang:>{width}}: {adj:>{width}}'
Out[582]: ' Python: Very Good'
You can fetch the padding value from the argument list:
print '%*s : %*s' % (20, "Python", 20, "Very Good")
You can even insert the padding values dynamically:
width = 20
args = ("Python", "Very Good")
padded_args = zip([width] * len(args), args)
# Flatten the padded argument list.
print "%*s : %*s" % tuple([item for list in padded_args for item in list])
Encase SHOWLEN in brackets
"{varname:<{SHOWLEN}.{SHOWLEN}f}".format(varname=34.54, SHOWLEN=8)
This is evident from the following quote from the Format String Syntax documentation:
A format_spec field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.
If using the f-string format.
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 {}
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().
Per the Python Format Specification Mini-Language, alignment specifiers (e.g. <) must precede the width specifier (e.g. 15). With this criteria in mind, the correct formulation for your format string is {:<15}. However, left-alignment is inferred by default for strings, so you can write this simply as {:15}.
>>> print(f'{"string":<15}|')
string |
>>> print(f'{"string":15}|')
string |
I think what you are looking for is simply print(f'{"string":15}|')