Day1:用户交互与格式化输出
Posted 中华酷联
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Day1:用户交互与格式化输出相关的知识,希望对你有一定的参考价值。
一、用户交互
input()方法
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Hiuhung Wan 4 5 username = input("Username:") 6 password = input("Password:") 7 print(username,password)
raw_input() python 2.x 与input() python 3.x是一样的
二、格式化输出
1.字符串拼接,使用加号“+”(不推荐使用)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Hiuhung Wan 4 name = input("name:") 5 age = input("age:") 6 job = input("job:") 7 salary = input("salary:") 8 info = ‘‘‘ 9 --------- info of ‘‘‘+ name + ‘‘‘ ---------- 10 Name:‘‘‘+ name +‘‘‘ 11 Age:‘‘‘+ age + ‘‘‘ 12 Job:‘‘‘+ job + ‘‘‘ 13 Salary:‘‘‘+salary 14 print(info)
2.用$占位符
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Hiuhung Wan 4 name = input("name:") 5 age = input("age:") 6 job = input("job:") 7 salary = input("salary:") 8 info = ‘‘‘ 9 --------- info of %s ---------- 10 Name:%s 11 Age:%s 12 Job:%s 13 Salary:%s 14 ‘‘‘%(name,name,age,job,salary) 15 print(info)
其中%s的s代表的是string,还有$d,$f
python中,默认的所有输入当作字符串
如果age改成$d,需要将用户的输入转格式,如int(),或str()
3.format方法一
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Hiuhung Wan 4 name = input("name:") 5 age = int(input("age:")) #integer 6 #print(type(age),type(str(age))) 7 job = input("job:") 8 salary = input("salary:") 9 info2 = ‘‘‘ 10 --------- info of {_name} ---------- 11 Name:{_name} 12 Age:{_age} 13 Job:{_job} 14 Salary:{_salary} 15 ‘‘‘.format(_name = name , _age = age, _job = job,_salary = salary) 16 print(info2)
4.format方法二
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:Hiuhung Wan 4 name = input("name:") 5 age = int(input("age:")) #integer 6 #print(type(age),type(str(age))) 7 job = input("job:") 8 salary = input("salary:") 9 info3 = ‘‘‘ 10 --------- info of {0} ---------- 11 Name:{0} 12 Age:{1} 13 Job:{2} 14 Salary:{3} 15 ‘‘‘.format(name,age,job,salary) 16 print(info3)
如果参数多,使用此方法容易弄错
以上是关于Day1:用户交互与格式化输出的主要内容,如果未能解决你的问题,请参考以下文章