How to insert string into a string as a variable?

前端 未结 7 560
野的像风
野的像风 2021-01-06 09:25

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 Enem         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-06 10:04

    The problem with your code is that you are using %d for the second argument. The %d is intended for integers, while %s is intended for strings. You can make it work by changing to %s like this:

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

    Output

    The Enemy's health is 0. The Enemy is dead.
    

    An alternative is to use the format function like this:

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

    More on string formatting can be found here.

提交回复
热议问题