好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

ThePythonTutorial#InputandOutput

[译]The Python Tutorial#Input and Output

Python中有多种展示程序 输出的方式;数据可以以人类可读的方式打印出来,也可以 输出到文件中以后使用。本章节将会详细讨论。

7.1 Fancier Output Formatting

目前为止已经介绍过两种 输出值的方式: 表达式语句 和 print() 函数。(第三种方式是使用对象的 write() 方法;使用 sys.stdout 引用标准 输出文件。详细信息参考库文件参考手册。)

有时候需要对 输出有更多的控制,而不是简单的使用空格分开值。有两种方式格式化 输出:第一种方式是手动处理字符串,使用字符串的切片和连接操作,创建任何可以想象到的 输出布局。字符串类型提供了一些将字符串填充到指定列宽的有用方法,马上会讨论这点。第二种方式是使用格式化字符串或者 str.format() 方法。

string 模块包含 Template 类,该类提供向字符串代入值的方法。

当然还有一个问题:如何将值转换为字符串?Python提供了将任何值转换为字符串的方法:将值传递给 repr() 或者 str() 函数即可。

str() 函数返回值的人类可读的形式,而 repr() 生成值的解释器可读形式(如果没有等价语法,将会强制抛出 SyntaxError )。对于没有提供特定适应人类阅读形式的对象, str() 函数会返回与 repr() 相同的值。许多值使用 str() 和 repr() 函数将得到相同的返回值,如数字或者像列表和字典的结构体。特别地,字符串有两种区别明显的表示形式。

以下是一些示例:

  >>>  s  =   'Hello, world.' 
 >>>   str (s)
 'Hello, world.' 
 >>>   repr (s)
 "'Hello, world.'" 
 >>>   str ( 1  /  7 )
 '0.14285714285714285' 
 >>>  x  =   10   *   3.25 
 >>>  y  =   200   *   200 
 >>>  s  =   'The value of x is '   +   repr (x)  +   ', and y is '   +   repr (y)  +   '...' 
 >>>   print (s)
The value of x  is   32.5 ,  and  y  is   40000 ...
 >>>   # The repr() of a string adds string quotes and backslashes: 
... hello  =   'hello, world  \n  ' 
 >>>  hellos  =   repr (hello)
 >>>   print (hellos)
 'hello, world\n' 
 >>>   # The argument to repr() may be any Python object: 
...  repr ((x, y, ( 'spam' ,  'eggs' )))
 "(32.5, 40000, ('spam', 'eggs'))"   

查看更多关于ThePythonTutorial#InputandOutput的详细内容...

  阅读:45次