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 {}
.