There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use.
7.1. Fancier Output Formatting
the standard output file can be referenced as
sys.stdout
.1
2
3'Hello\n') sys.stdout.write(
Hello
6Formatted string literally, add
f
orF
before a single or triple quotation, wrap variable or expression in{}
1
2
3
4
52021 a =
'Python' b =
f'Learn {b} in {a}' s =
s
'Learn Python in 2021'str.format() can make more complex format
using string slicing and concatenation operations to create any layout you can imagine.
you can convert any value to a string with the repr() or str() functions.
7.1.1. Formatted String Literals
Passing an integer after the
:
will cause that field to be a minimum number of characters wide. This is useful for making columns line up.1
2
3
4
5
6f'the res is {res:<20}|'
'the res is 3.423452154 |'
f'the res is {res:^20}|'
'the res is 3.423452154 |'
f'the res is {res:>20}|'
'the res is 3.423452154|'Other modifiers can be used to convert the value before it is formatted.
!a
appliesascii()
,!s
appliesstr()
, and!r
appliesrepr()
:1
2
3
4
5'eels' animals =
f'My hovercraft is full of {animals}.') print(
My hovercraft is full of eels.
f'My hovercraft is full of {animals!r}.') print(
My hovercraft is full of 'eels'.see more at Format Specification Mini-Language
7.1.2. The String format() Method
A number in the brackets can be used to refer to the position of the object passed into the
str.format()
method.1
2'{1} and {0}'.format('spam', 'eggs')) print(
eggs and spamkeyword arguments are referred by their keys
1
2
3'This {food} is {adjective}.'.format( print(
'spam', adjective='absolutely horrible')) food=
This spam is absolutely horrible.dictionary unpacking is useful
1
2
3'name' : 'Jack' , 'age':24} dic = {
'His name is {name} and age is {age}'.format(**dic)
'His name is Jack and age is 24'7.1.3. Manual String Formatting
The
str.rjust()
method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left, similar methods arestr.ljust()
andstr.center()
.They just return a new string
They do not truncate strings, if you really want to truncate surplus part, use
x.ljust(n)[:n]
to make a slicing.1
2
3
4
5
6'hello'.rjust(10)
' hello'
'hello'.ljust(10)
'hello '
'hello'.center(10)
' hello 'str.zfill()
, which pads a numeric string on the left with zeros. It understands about plus and minus signs:1
2
3
4
5
6'12'.zfill(5)
'00012'
'-3.14'.zfill(7)
'-003.14'
'3.14159265359'.zfill(5)
'3.14159265359'7.1.4. Old string formatting
Given
'string' % values
, instances of%
instring
are replaced with zero or more elements ofvalues
.(This method is very C like)
1
2
3
4
5import math
'The value of pi is approximately %5.3f.' % math.pi) print(
The value of pi is approximately 3.142.
'a = %d b = %f' % (2000,3.14)) print(
a = 2000 b = 3.140000see more at printf-style String Formatting
7.2. Reading and Writing Files
file = open('filename' , 'mode')
, The mode argument is optional;'r'
will be assumed if it’s omitted.when I/O text encoding can be specified, If encoding is not specified, the default is platform dependent (see
open()
)add
'b'
to mode character to I/O binary, which represented by bytes objects in PythonIn text mode, the default when reading is to convert platform-specific line endings, you write the
\n
in your source code, but Unix Python use\n
, Windows Python use\r\n
, when actually write to the file.The advantage of using
with
is that the file is properly closed after its suite finishes, even if an exception is raised at some point.If the do file.write() without file closing, the content may not be writen to the disk,even Python exit successfully!!!
7.2.1. Methods of File Objects
f.read(size)
, size is a numerical number, the method reads size character in text mode, reads size bytes in binary mode, if not given, read the whole file.It will read from the latest position! Return a ‘’ when reach the end
1
2$ cat text
HelloWorld1
2
3
4
5
6
7
8
9open ('text' , 'rt') f =
5) f.read(
'Hello'
5) f.read(
'World'
5) f.read(
'\n'
5) f.read(
''f.readline()
reads a single line from the file; a newline character (\n
) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. Return a''
when reach the end of the file.1
2
3
4
5
6f.readline()
'This is the first line of the file.\n'
f.readline()
'Second line of the file\n'
f.readline()
''use
list(f)
orf.readlines()
to read as alist
, or directly use a loop1
2
3
4
5for line in f:
'') print(line, end=
...
This is the first line of the file.
Second line of the filef.write(string)
writes the contents of string to the file, returning the number of characters written.1
2'This is a test\n') f.write(
15Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary mode) – before writing them
f.tell()
returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number(should only be used to pass to aseek()
, otherwise meaningless) when in text mode.f.seek(offset, whence)
. The position is computed from adding offset to a reference point; the reference point is selected by the whence argument.whence = (default is 0) position 0 beginning of the file 1 current position 2 end of the file In text mode, only seeks relative to the beginning of the file are allowed, only the return value of
tell()
or 0 is a valid value for whence.
7.2.2. Saving structured data with json
When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated.
The standard module called
json
can take Python data hierarchies, and convert them to string representations; this process is called serializing. Reconstructing the data from the string representation is called deserializing.If you have an object x, you can view its JSON string representation with a simple line of code:
1
2
3
4
5
6
7import json
'ewf',123] ls = [
s= json.dumps(ls)
s
'["ewf", 123]'
type(s)
<class 'str'>dump()
, simply serializes the object to a text file. So iff
is a text file object opened for writing1
2with open('serialization','w+') as f:
json.dump(ls,f)1
2
3$ cat serialization
["ewf", 123]%
# (% means no newline)To decode the object again, if
f
is a text file object which has been opened for reading1
2
3
4
5
6
7open('serialization') f =
import json as j
x = j.load(f)
x
['ewf', 123]
type(x)
<class 'list'>to convert
Python Class
to json see more at jsonpickle is a protocol which allows the serialization of arbitrarily complex Python objects, and it is specific to Python Only.
deserializing pickle data coming from an untrusted source can execute arbitrary code!!!