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

5
  • 1
    Keep it simple... var_a + ' world' Commented Apr 12, 2017 at 11:30
  • It is not simple as you are saying. You have only string containing var names. Just need to evaluate variable which are unknown Commented Apr 12, 2017 at 11:48
  • 1
    Your question has no unknown variables Commented Apr 12, 2017 at 11:59
  • You dont know which variable will come in picture Commented Apr 12, 2017 at 13:15
  • I don't know what that means, but if you want to format a string using a variable, that variable must be "in scope". The contents of that variable doesn't matter. Commented Apr 12, 2017 at 14:50

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

6 Comments

what if you dont know variable name in string?
@Swapnil Look at the second code block. The variable you insert (var_a) must be defined
var_a is not fixed variable how you add it format then?
@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?
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).
|
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

1 Comment

You just have clean string and have to evaluate variables like ruby package = "Interpy" print "Enjoy #{package}!"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.