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中的变量是对应的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值