020 格式化输出的三种方式
格式化输出的三种方式
符合某种规范的打印输出
1.占位符
程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式
比如要求用户输入用户名和年龄,然后打印如下格式:My name is xxx,my age is 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
2.format格式化
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.
3.f-Strig格式化
相比较占位符的方式,python3.6版本新增了f-String格式化的方式,比较简单易懂,这是目前我用的最多的方式,推荐使用这种方式。
1.让字符串和数字可以直接相加
name = "nick"
age = 19
print(f"Hello, {name}. You are {age}.")
Hello, nick. You are 19.
2.大写的F也适用。
name = "nick"
age = 19
print(F"Hello, {name}. You are {age}.")
Hello, nick. You are 19.
age = 19
print(f'{age*2}')
38
3.F-string格式化方法还可直接转换成浮点型,以及保留几位小数
s1 = 'nick' # name
s2 = 'ugly' # qizhi
s3 = 180 # height
print(f'name:{s1}, qizhi:{s2:->10}, height:{s3:.2f}')
name:nick, qizhi:------ugly, height:180.00