Python Tutorial 学习笔记5 --IO

来源:互联网 发布:3m易清洁涂层 知乎 编辑:程序博客网 时间:2024/06/11 05:41

There are two ways to format your output; the first way is to do all the string handling yourself; using string slicing and concatenation operations you can create any layout you can imagine. The string types have some methods that perform useful operations for padding strings to a given column width; these will be discussed shortly. The second way is to use the str.format() method.

One question remains, of course: how do you convert values to strings? Luckily, Python has ways to convert any value to a string: pass it to therepr() or str() functions. The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter.

例1:


例2:the str.rjust() method of string objects, which right-justifies a string in a field of a given width by padding it with spaces on the left.There are similar methods str.ljust() and str.center().


例3:There is another method, str.zfill(), which pads a numeric string on the left with zeros.


例4:The brackets and characters within them (called format fields) are replaced with the objects passed into the str.format() method. A number in the brackets refers to the position of the object passed into thestr.format() method.


例5:'!s' (apply str()) and '!r' (apply repr()) can be used to convert the value before it is formatted.


例6:Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.


NOTES:This could also be done by passing the table as keyword arguments with the ‘**’ notation.

例7:Old string formatting. The % operator can also be used for string formatting.


例8:open() returns a file object, and is most commonly used with two arguments:open(filename, mode).






例9:It is good practice to use the with keyword when dealing with file objects.It is also much shorter than writing equivalent try-finally blocks.

 

例10:data exchange with json


例11:If f is a file object opened for writing, we can use dumps() serializes the object to a file.



0 0
原创粉丝点击