Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert string into a string as a variable?

I'm trying to create a program and one thing I'm trying to do is add variables to a string like so.

EnemyHealth = 0  

EnemyIs = 'dead'

print("The Enemy's health is %d. The Enemy is %d." % (EnemyHealth,EnemyIs)

But everytime I try that it won't let me use a string as one of the variables. How would I insert a variable string into another string?

P.S. I am using python 3.7.0

like image 337
PLP123 Avatar asked Sep 03 '18 19:09

PLP123


People also ask

How do you assign a string to a string variable?

How to create a string and assign it to a variable. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable.

How do you add a string variable to a string in Python?

You can use the string method format method to create new strings with inserted values. This method works for all current releases of Python. Here we insert a string into another string: >>> shepherd = "Mary" >>> string_in_string = "Shepherd {} is on duty.".

How do you add text to a variable in Python?

You can append another string to a string with the in-place operator, += . The string on the right is concatenated after the string variable on the left. If you want to add a string to the end of a string variable, use the += operator.


2 Answers

There are 4 approaches I am aware of for achieving this on python (Python 3):

1) Concatenation:

You can do this using + for joining 2 strings, however you can only concatenate string type data, meaning non string type data needs to be converted to string using the str() function. For example:

print("The Enemy's health is " + str(EnemyHealth) + ". The Enemy is " + EnemyIs + ".") 
# output = "The Enemy's health is 0. The Enemy is dead." 

2) Taking advantage of Python 3's print() function which can take multiple parameter arguments:

Here your print() statement similar to the concatenation statement above, except where ever I use + to concatenate you need to replace it with ,. The advantage of using this, is that different data types will be automatically converted to string, i.e. no longer needing the str() function. For example:

print("The Enemy's health is ", EnemyHealth, ". The Enemy is ", EnemyIs, ".") 
# output = "The Enemy's health is 0. The Enemy is dead." 

3) Using your string replacement approach

The reason your code doesnt work, is because %d means you will replace it with an integer and therefore to make your code work, for the string stored on the variable EnemyIs needs to be replaced with %s which is used to state that it will be replaced with a string. Therefore to solve your problem you need to do:

print("The Enemy's health is %d. The Enemy is %s." % (EnemyHealth, EnemyIs)) 
# output = "The Enemy's health is 0. The Enemy is dead." 

4) The format() method for python strings (This is the best approach to use)

This is a built in method for all strings in python, which allow you to easily replace the placehoder {} within python strings, with any variables. Unlike solution number 3 above, this format() method doesnt require you to express or convert different data types to string, as it would automatically do this for you. For example, to make your print statement work you can do:

print("The Enemy's health is {}. The Enemy is {}.".format(EnemyHealth, EnemyIs)) 

OR

print("The Enemy's health is {0}. The Enemy is {1}.".format(EnemyHealth, EnemyIs)) 

# output = "The Enemy's health is 0. The Enemy is dead." 

UPDATE:

5) F-Strings

As of python 3.6+, you can now also use f-strings, to substitute variables within a string. This method is similar to the the .format() method described above, and in my oppinion is a better upgrade to the str.format() method. To use this method all you have to do is state f before your opening quote when defining a string and then, within the string use the format, {[variable name goes here]} for this to work. For example, to make your print statement work, using this method, you can do:

print(f"The Enemy's health is {EnemyHealth}. The Enemy is {EnemyIs}.")
# output = "The Enemy's health is 0. The Enemy is dead." 

As you can see by using this method, the variable name is being instanciated directly within the curly brackets {}.

like image 111
SShah Avatar answered Oct 21 '22 12:10

SShah


Avoid % format specifiers in Python3.x

From the Docs :

old style of formatting will eventually be removed from the language, str.format() should generally be used.

There are few simple ways to do this, check below code :

print("The Enemy's health is {} The Enemy is {}".format(EnemyHealth, EnemyIs)

print("The Enemy's health is {0} The Enemy is {1}".format(EnemyHealth, EnemyIs)

print("The Enemy's health is {EnemyHealth} The Enemy is {EnemyIs}".format(EnemyHealth=EnemyHealth, EnemyIs=EnemyIs)
like image 4
Vishvajit Pathak Avatar answered Oct 21 '22 12:10

Vishvajit Pathak