目录
- 占位符(掌握)
- fORMat格式化(了解)
- f-String格式化(掌握)
程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式
比如要求用户输入用户名和年龄,然后打印如下格式:My name is xxx,my age is xxx.
很明显,用逗号进行字符串拼接,只能把用户输入的名字和年龄放到末尾,无法放到指定的xxx位置,而且数字也必须经过str(数字)的转换才能与字符串进行拼接,非常之麻烦,我们来试一试。
age = 19
print('My name is xxx,my age is '+str(age))
My name is xxx,my age is 19
age = 19
print('My name is xxx,my age is', age)
My name is xxx,my age is 19
name = 'nick'
age = 19
print('My name is '+name+' my age is '+str(age))
My name is nick my age is 19
上面使用的方法越看越别扭,越看越麻烦。这就需要用到占位符,如:%s(针对所有数据类型)、%d(仅仅针对数字类型)
name = 'nick'
age = 19
print('my name is %s my age is %s' % (name, age))
my name is nick my age is 19
age = 19
print('my age is %d' % age)
my age is 19
讲真,很鸡肋的格式化的方法,如果你需要使用这个,遇到多参数的时候,还是需要在句子后面噼里啪啦传上一大堆参数。使用这个不如用占位符或下面的f-String格式化。
name = 'nick'
age = 19
print("Hello, {}. You are {}.".format(name, age))
Hello, nick. You are 19.
name = 'nick'
age = 19
print("Hello, {1}. You are {0}-{0}.".format(age, name))
Hello, nick. You are 19-19.
name = 'nick'
age = 19
print("Hello, {name}. You are {age}-{age}.".format(age=age, name=name))
Hello, nick. You are 19-19.
相比较占位符的方式,python3.6版本新增了f-String格式化的方式,比较简单易懂,这是目前我用的最多的方式,推荐使用这种方式。
name = "nick"
age = 19
print(f"Hello, {name}. You are {age}.")
Hello, nick. You are 19.
大写的F也适用。
name = "nick"
age = 19
print(F"Hello, {name}. You are {age}.")
Hello, nick. You are 19.
age = 19
print(f'{age*2}')
38
再给你秀个以后可能会用到的操作。
salary = 6.6666
print(f'{salary:.2f}')
6.67
0