python对于格式的三种控制方法

久未见 提交于 2020-02-22 20:47:09

一、f‘xxx {a}’

前面加 f 后面变量加上大括号,要有变量,且引用的时候要被扩起来
print(f’{xxx}’)
example 01

>>> event = 'tornado'
>>> year = 2005.123456
>>> print(f'There is an {event} in {year:.3f}') #保留小数的位数
There is an tornado in 2005.123

【d保证的是整数,f保证的是小数】
example 02

a = str(input('please input the first name: '))
b = str(input('please input the second name: '))
print(f'{a} and {b} are helping each other.')
please input the first name: wyb
please input the second name: xz
wyb and xz are helping each other.

二、print(’{} xxx {}’.format(a,b))

*是最常用的格式输出
print(’{} xxx {}’.format(a,b))
位置指定时,第一个是0 第二个是1

a = str(input('please input the first name: '))
b = str(input('please input the second name: '))
print('{} and {} are caring about each other.'.format(a,b))
please input the first name: wyb
please input the second name: xz
wyb and xz are caring about each other.

三、’%d xxx %d‘%(a,b,c)

每个百分号% 后面都要有对于其类型的定义

a = str(input('please input the first name: '))
b = str(input('please input the second name: '))
print('%s and %s are hard-working.'%(a,b))    # s代表的是字符型 d代表的是数值型

[s代表的是字符型 d代表的是数值型且保留整数 f代表的是数值型且保留小数]

please input the first name: wyb
please input the second name: xz
wyb and xz are hard-working.

=================================

四、例子🌰

以下为分别用三种方法实现同样的结果:

a = int(input('a='))
b = int(input('b='))
print('%d + %d= %d'%(a,b,a+b))
print('{} * {}= {}'.format(a,b,a*b))
print(f'{a} % {b}= {a%b}')
a=7
b=2
7 + 2= 9
7 * 2= 14
7 % 2= 1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!