This section learns about Python's formatted output, file manipulation, and the simple use of JSON
1. Formatted output
To convert a non-string type to a string, you can use the function: str () or repr (), (the difference between these two functions I still do not understand, ask for answers )
>>> STR ([1,2,3,4])'[1, 2, 3, 4]'>>> repr ([1,2,3,4]) ' [1, 2, 3, 4] '>>> str ' >>>repr (Ten)' ten'
You can use Str.ljust (), Str.rjust (), Str.center () to set the alignment of a string
for in range (1,11): Print str (x). Ljust (2), str (x*x). Ljust (3), str (x*x*x). Ljust (4) 1 1 1 2 4 8 3 9 + 4 + 5 6 216 7 343 8 9 bayi 729 10 100 1000
We can also use Str.format () to set the alignment of the string ({} fill ^, <, > center, Align Left, align Right ):
for in range (1,11): print"{0:<2d} {1:<3d} {2:<4d}" . Format (x,x*x,x*x*x) 1 1 1 2 4 8 3 9 4 16 5 6 216 7 343 8 + 9 bayi 729 10 100 1000
Other ways to use Str.format ():
>>> print "His name was {},his age is {}". Format (' Jack ', 30)
His name is Jack,his 30
>>> print "His name was {1},his age is {0}". Format (' Jack ')
His name is Jack,his 30
>>> print "His name was {Name},his age was {age}". Format (age=30,name= ' Jack ')
His name is Jack,his 30
>>> print "PI is {0:.2f}". Format (3.1415926)
Pi is 3.14
>>> t={' name ': ' Jack ', ' Age ': 30}
>>> print "His name was {0[name]:s},his age is {0[age]:d}". Format (t)
His name is Jack,his 30
>>> print "His name was {Name:s},his age is {age:d}". Format (**t)
His name is Jack,his 30
We also have a format for the output form, as follows:
Print " Pi is%.2f " % (3.1415926 is 3.14
Python Learning Notes (11th lesson)