3

var_a (can be any variable name) should be replaced by its value:

var_a = "Hello"

var_b = "var_a world"

print var_b

Output should be: Hello world

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Swapnil
  • 191
  • 2
  • 9

2 Answers2

1

That exactly fits the str.format description. You need to wrap the "part of the string you want to replace" with curly braces:

var_a = "Hello"

var_b = "{var_a} world".format(var_a=var_a)

It's also possible to use it without "names":

var_b = "{} world".format(var_a)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • what if you dont know variable name in string? – Swapnil Apr 12 '17 at 11:57
  • @Swapnil Look at the second code block. The variable you insert (var_a) must be defined – OneCricketeer Apr 12 '17 at 12:00
  • var_a is not fixed variable how you add it format then? – Swapnil Apr 12 '17 at 12:04
  • @Swapnil Do I understand you correctly: You don't know in advance which _part of the string_ you want to replace? Or is it the variable name that should be dynamic? – MSeifert Apr 12 '17 at 12:05
  • Yes like ruby package = "Interpy" print "Enjoy #{package}!" – Swapnil Apr 12 '17 at 12:11
  • 1
    in that case I would advise to upgrade to python 3.6 and use f-strings: `var_b = f"{var_a} world"`. :) (you could use workaround to make it work on python 2.7 but it would be terribly inefficient and error prone). – MSeifert Apr 12 '17 at 12:14
0

That is called variable substitution. You can do it by using format characters string formatting / interpolation operator in python. The code you wrote above would not work as you are expecting it to work.

For example, if you want to get the output you want to with variable substitution, you can do something like:

var_a = "Hello"
var_b = "%s world" % var_a
print var_b

This will output Hello world.

Documentation

  • You just have clean string and have to evaluate variables like ruby package = "Interpy" print "Enjoy #{package}!" – Swapnil Apr 12 '17 at 12:23