Python学习笔记

Python的输出和输入

2016-08-24  本文已影响143人  Viking_Den

Python的输出

常见的Python输出是使用print内建函数,或者输出到文件,或者输出到数据库,本文的输出主要是介绍print函数,下面是使用help方法查看print的说明:


help(print).png

从上图可以看出,print函数的默认分隔符是一个空格,默认在最后加上换行符。

简单输出:
Python简单输出.png
格式化输出:
python格式化输出.png
format()函数:
  1. 通过位置替换

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’。

>>> print ('{0} {1}'.format('hello','world'))
hello world  
>>> print ('{} {}'.format('hello','world'))
hello world  
>>> print ('{0} {1} {0}'.format('hello','world'))
hello world hello  

在字符串模板中确定位置,并且位置可以不按顺序,format()可传入任意数目的参数。

  1. 关键字替换

也可以采用关键字替换的方法。

>>> print ('i love {python}'.format(python='you'))  
i love you 
  1. 其他使用方法

如可以指定输出长度和输出的对齐方式,其中对齐方式有一下几种:

>>> print (format(3.14151617,'.5f')) 
3.14152  
>>> print ('{0:>10}'.format('sqxu'))    #10个占位符,右对齐  
      sqxu  
>>> print ('{0:4.2f}'.format(3.141516))
3.14  
>>> print ('{0:6.2f}'.format(3.141516)) 
  3.14  
>>> print ('{0:>6.2f}'.format(3.141516)) 
  3.14  
>>> print ('{1:<10},{0:<15}'.format('sqxu','USTC'))  
USTC      ,sqxu             
>>> print ('name={name},age={age}'.format(name='sqxu',age=25))  
name=sqxu,age=25
如何让 print 不换行:

在Python中总是默认换行的.如果想要不换行,之前的 2.x 版本可以这样 print x, 在末尾加上 ,但在 3.x 中这样不起任何作用,要想换行你应该写成 print(x,end = '' )。

Python的输入

input函数,注意:python2.x版本对应为raw_input函数

python input function.png

接受一个标准输入数据,返回为string类型,prompt为提示信息。


input.png
上一篇 下一篇

猜你喜欢

热点阅读