Home Function and Console I/O
Post
Cancel

Function and Console I/O

formatting output

  • %, format, fstring

%

1
2
print('%s %s' % ('hello', 'jason'))
print('%d %s %f' % (10, 'jason', 10.2))
hello jason
10 jason 10.200000
1
2
print("%10s" % ("Jason"))
print("%10.5f" % (1/7))
     Jason
   0.14286
1
print("Name: %(name)10s" % {"name":"jason"})
Name:      jason

.format()

1
2
3
4
print('hello {} my name if {}'.format("jason","chilla"))
print('hello {0} my name if {1}'.format("jason","chilla"))
print('hello {0:10.5f} my name if {1}'.format(1/7,"chilla"))
print('hello {you} my name if {me}'.format(you="jason", me="chilla"))
hello jason my name if chilla
hello jason my name if chilla
hello    0.14286 my name if chilla
hello jason my name if chilla

padding

1
print("Name: {:>20.5}".format("Jason"))
Name:                Jason

fstring

1
2
3
4
5
6
7
8
name = "Jason"
age = 26
school = "skrt"
amount = 254.2
print(f"{name:*>20}")
print(f"{name:*<20}")
print(f"{name:*^20}")
print(f"{amount:.2f}")
***************Jason
Jason***************
*******Jason********
254.20
This post is licensed under CC BY 4.0 by the author.
Trending Tags