python的基本输入输出

python的输入输出

输入:

input(),   raw_input()

1.     input():    用于收集数字输入

>>>a=input("input a:")

input a:2

>>> a

2

#可以输入一个变量:

>> a=input("inputa:")

input a:a

>>> a

2

#无法接收字符

>>>a=input("input a:")

input a:b

Traceback (mostrecent call last):

     File "<pyshell#7>", line 1,in <module>

   a=input("input a:")

     File "<string>", line 1, in<module>

NameError: name'b' is not defined

2.     raw_input():把用户输入的任何内容都保存为一个字符串;

>>>a=raw_input('input a:')

input a:2

>>> a

'2'

3.     强制类型转换

>>>a='2'

>>>b=float(a)

>>> b

2.0

不能转换则会抛出错误

4.     密码输入

python 自带了一个库 getpass

>>>from getpass import getpass

>>>password=getpass()

password:

>>>password

'rrrr'

5.     清理用户的输入

使用strip()函数

6.     格式化输出

对字符串使用format()函数

例1

>>>greeting='Good {} ,{} are fine!'

>>>time='morning'

>>>people='I'

>>>print greeting.format(time,people)

Good morning ,I are fine!

花括号的值和format()中的变量一一对应

例2

greeting='Good{time}, {people} are fine'

>>>print greeting.format(time='morning',people='I')

Good morning,I are fine

>>>greeting

'Good{time}, {people} are fine'

>>>time='morning'

>>>people='I'

>>>print greeting.format(time=time,people=people)

Good morning, I are fine

例3

       people='{0},{1},{2}'

>>> print people.format('students','teachers','parents')

students,teachers,parents

花括号中的值从0开始

people='{2}'

>>> print people.format('students','teachers','parents')

parents

花括号中的标号,和format中的变量是对应的

猜你喜欢

转载自blog.csdn.net/bookwormsmallman/article/details/51146124