以如下打印为例:
my name is tom and my age is 12
方式一
name = 'tom' age = 12 print(f"my name is {name} and my age is {age}")
方式二
name = 'tom' age = 12 print("my name is " + name + " and my age is " + str(age))
方式三
name = 'tom' age = 12 print("my name is %s and my age is %s" %(name,age))
方式四
name = 'tom' age = 12 print("my name is {name} and my age is {age}".format(name='tom',age=12))
方式五
print("my name is {} and my age is {}".format('tom',12))
方式六
name = 'tom' age = 12 print("my name is {} and my age is {}".format(name,age))
注意以下调用反而会引起错误
name = 'tom' age = 12 print("my name is {name} and my age is {age}".format(name,age)) Traceback (most recent call last): File "<pyshell#586>", line 1, in <module> print("my name is {name} and my age is {age}".format(name,age)) KeyError: 'name'
方式七
注意format两个参数的赋值顺序:
print("my name is {1} and my age is {0}".format(12,'tom'))
方式八
says = "my name is %s and my age is %s" value =('tom', 12) says%value
注意 在字典(以及其他映射类型)中,键必须是独一无二的,而字典中的值无需如此。
来源:https://www.cnblogs.com/sindweller/p/12653911.html