格式化输出
占位符
程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式
打印如下格式: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
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.
f-String格式化
相比较占位符的方式,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.