文档介绍:: .
Python 输入和输出 菜鸟教程
Python 输入和输出 在前面几个章节中,我们其实已经接触了 Python 的输入输 出的功能。本章节我们将具体介绍 Python 的输入输出。
输出格式美化
Python 两种输出值的方式 : 表达式语句和 print() 函数。 (第 三种方式是使用文件对象的 write() 方法 ; 标准输出文件可 以用 引用。 )
如果你希望输出的形式更加多样,可以使用 () 函 数来格式化输出值。
如果你希望将输出的值转成字符串, 可以使用 repr() 或 str() 函数来实现。
str() 函数返回一个用户易读的表达形式。
repr() 产生一个解释器易读的表达形式。
例如
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'**********'
>>> x = 10 *
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' >>> print(s)
The value of x is , and y is 40000...
>>> # repr() 函数可以转义字符串中的特殊字符
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # repr() 的参数可以是 Python 的任何对象
... repr((x, y, ('spam', 'eggs')))
"(, 40000, ('spam', 'eggs'))"
这里有两种方式输出一个平方与立方的表
>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # 注意前一行 'end' 的使用
... print(repr(x*x*x).rjust(4))
1
1
1
2
4
8
3
9
27
4
16
64
5
25
125
6
36
216
7
49
343
8
64
512
9
81
729
10 100 1000
>>> for x 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
27
4
16
64
5
25
125
6
36
216
7
49
343
8
64
512
9
81
729
10 100 1000
注意:在第一个例子中 , 每列间的空格由 print() 添加。
这个例子展示了字符串对象的 rjust() 方法 , 它可以将字符 串靠右 , 并在左边填充空格。
还有类似的方法 , 如 ljust() 和 center() 。 这些方法并不会写 任何东西 , 它们仅仅返回新的字符串。
另一个方法 zfill(), 它会在数字的左边填充 0,如下所示: >>> '12'.zfill(5)
'00012'
>>> '-'.zfill(7)
'-'
>>> '3.**********'.zfill(5)
'3.**********'
() 的基本使用如下 :
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
括号及其里面的字符 (称作格式化字段 ) 将会被 format() 中的参数替换。
在括号中的数字用于指向传入对象在 format() 中的位置, 如 下所示:
>>> print('{0} and {1}'.format('spam', 'eggs')) spam and eggs
>>> print('{1} and {0}'.for