将变量替换为字符串

时间:2016-10-14 13:17:12

标签: python string python-2.7

目前我知道我们可以做类似

的事情
"This is a string with var %(sub_var)s that will be substituted" % ({'sub_var': 'a1234'})

sub_var变量中的子变量放入字符串中。但是有一种方法来定义这样的字符串:

a = "This is a string with var %(sub_var)s that will be substituted"

在实际使用字符串sub_var之前,不定义a?我有一些变量可以根据条件改变,我不想继续重新输入a

谢谢!

2 个答案:

答案 0 :(得分:3)

你是否完全按照你所说的去做了?

   a = "This is a string with var %(sub_var)s that will be substituted"
=> None
   a
=> 'This is a string with var %(sub_var)s that will be substituted'
   a % {'sub_var': 'c'}
=> 'This is a string with var c that will be substituted'

答案 1 :(得分:0)

将函数存储在可用于创建字符串的变量中:

>>a='Variable is {}'.format
>>print(a('one'))
Variable is one
>>print(a('two'))
Variable is two