python字符串调用举例

爱⌒轻易说出口 提交于 2020-04-07 20:48:15

以如下打印为例: 

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

 

 

 

 

注意 在字典(以及其他映射类型)中,键必须是独一无二的,而字典中的值无需如此。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!