1.12 Formatting Strings
The formatting string uses a structure {X:>0Y.ZW}
.
Here is what each (X
,Y
,>
,0
,Z
,W
) represent:
W |
Specifies the type of variablef - floatd - integers - stringg - Ask python figure out |
X |
Variable to format (Can be a number or a string) |
> |
Alignment Use < , > , ^ for Left, Right and Centre |
Y |
Total number of characters |
Z |
Number of decimal places |
0 |
Use 0’s to pad the spaces |
1.12.0.1 Python 3.6 and newer
Python 3.6 introduced somthing called ‘string interpolations’ which makes formatting even easier than before.
= 22/7
i
print(f'{i}') # Just print the number
# 3.142857142857143
print(f'{i:10.3f}') # Total of 10 spaces, 3 decimal points,
# 3.143
print(f'{i:<10.3f}') # Aligment: Left
# 3.143
print(f'{i:^10.3f}') # Aligment: Centre
# 3.143
print(f'{i:>10.3f}') # Aligment: Right
# 3.143
print(f'{i:010.3f}') # Total of 10 spaces, 3 decimal points,padded with 0's
# 000003.143
Refer to this website for more information.
1.12.0.2 Previous versions
= '{:>5} is {} years old today'.format('Mary',10)
text print(text)
# Mary is 10 years old today
= 'Integer: {:}\tFloat: {}'.format(1,1)
text print(text)
# Integer: 1 Float: 1