码迷,mamicode.com
首页 > 编程语言 > 详细

python用户交互与格式化输出

时间:2019-11-02 21:50:24      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:计算机   函数   fine   类型   module   pre   mode   使用   姓名   

一.python语法入门之与用户交互

1.1 什么是与用户交互

用户交互就是人往计算机中input/输入数据,计算机print/输出结果

1.2 为什么要进行用户交互

为了让计算机能够像人一样与用户沟通交流

1.3 如何与用户交互

交互的本质就是输入、输出

1.3.1 输入input:

在python3中input会等待用户的输入,无论用户输入的是什么类型,返回的一定是字符串(str)

>>> name = input(‘请输入你的用户名: ‘)
请输入你的用户名: bing
>>> type(name)
<class ‘str‘>
>>> name = input(‘请输入你的用户名: ‘)
请输入你的用户名: 123
>>> type(name)
<class ‘str‘>
>>> name = input(‘请输入你的用户名: ‘)
请输入你的用户名: [7, 8, 9]
>>> type(name)
<class ‘str‘>
>>>

PS:在python2中input一定要指定输入的类型

python2中的raw_input的功能与python3中的input的功能一样

>>> input(">>:")
>>:sean #未加引号,识别不出该输入内容是为字符串类型
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name ‘sean‘ is not defined
>>> input(">>:")
>>:"sean"  
‘sean‘
>>> input(">>:")
>>:1
1
>>> input(">>:")
>>:[1,2]
[1, 2]
>>>
?
1.3.2 输出print:
>>> print(‘hello world‘)
hello world
>>>
1.3.3 格式化输出

1 什么是格式化输出

把一段字符串里面的某些内容替换掉之后再输出,就是格式化输出。

2 为什么要格式化输出?

为了将某种固定格式的内容进行替换

3 怎么格式化输出?

引入占位符,如:%s  %d

>>> name = ‘bing‘
>>> like = ‘money‘
>>> print(‘My name is %s, My favorite is %s‘ %(name, like))
My name is bing, My favorite is money
>>> print(‘My name is %s, My favorite is %d‘ %(name, like))
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>>
?
>>> name = ‘bing‘
>>> age = 18
>>> print(‘My name is %s, My age is %d‘ %(name,age ))
My name is bing, My age is 18
>>> print(‘My name is %s, My age is %s‘ %(name,age ))
My name is bing, My age is 18
>>>

从上面的代码中我们不难看出,%s占位符可以接受任意类型的值;而%d占位符只能接受数字

.format

该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

>>> name = ‘bing‘
>>> age = 21
>>> print("name:{user},age:{age}".format(user=name,age=age))
name:bing,age:21
>>>

f-string

定义:被称为格式化字符串常量(formatted string literals),Python3.6新引入的一种字符串格式化方法。

用法:f-string在形式上是以 f 或 F 修饰符引领的字符串,以大括号 {} 标明被替换的字段,即f‘{},{}‘;f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式。

1.f-string解析变量(变量类型为str,int)

>>> name = ‘bing‘
>>> age = 21
>>> print(f‘name:{name},age:{age}‘)
name:bing,age:21
>>>

2.变量类型为列表,字典等

>>> dict = {‘name‘:‘bing‘, ‘age‘:18, ‘like‘:[‘running‘, ‘dancing‘]}
>>> print(f‘姓名: {dict["name"]}, 爱好: {dict["like"]}‘)
姓名: bing, 爱好: [‘running‘, ‘dancing‘]
>>>

保留两位小数

>>> a = 11111.22222
>>> print(‘%.2f‘%a)
11111.22
>>>

python用户交互与格式化输出

标签:计算机   函数   fine   类型   module   pre   mode   使用   姓名   

原文地址:https://www.cnblogs.com/a736659557/p/11784228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!