您的位置:首页 > 编程语言 > Python开发

Python Tutorial 学习笔记5 --IO

2016-07-08 15:11 429 查看
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 the
repr()
 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 the
str.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.



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python