python从字符串中的变量名称打印字符串

时间:2017-11-25 06:42:35

标签: python string

我想要显示文字。在文本中有一个变量名称,变量的名称已经在上一个定义中。

示例代码

my_dict = {}
my_dict['name']='Candra'

#I want to be like this
print('my name is {name}')

#not like this
print('my name is '+ my_dict['name'])

2 个答案:

答案 0 :(得分:0)

这样做的一种方法:

print "my name is {}".format(my_dict['name'])

输出:my name is Sandra

其他方式:print "my name is %s" % my_dict['name']

答案 1 :(得分:0)

你可以使用python 3

轻松完成
my_dict = {}
my_dict['name']='Candra'
name = my_dict['name']


a = f"He said his name is {name}."
print(a) 

输出

He said his name is Candra.