我知道有4种方法可以在python(Python 3)上实现:
您可以使用此方法+
来连接2个字符串,但是只能连接字符串类型数据,这意味着需要使用该str()
函数将非字符串类型数据转换为字符串。例如:
print("The Enemy's health is " + str(EnemyHealth) + ". The Enemy is " + EnemyIs + ".")
# output = "The Enemy's health is 0. The Enemy is dead."
在这里,您的print()
语句类似于上面的连接语句,除了我+
用来连接的地方外,您需要将其替换为,
。使用此方法的好处是,不同的数据类型将自动转换为字符串,即不再需要该str()
函数。例如:
print("The Enemy's health is ", EnemyHealth, ". The Enemy is ", EnemyIs, ".")
# output = "The Enemy's health is 0. The Enemy is dead."
您的代码不起作用的原因是,这%d
意味着您将用整数替换它,从而使您的代码正常工作,因为存储在变量上的字符串EnemyIs
需要替换%s
为用于声明将被字符串替换的字符串。因此,要解决您的问题,您需要执行以下操作:
print("The Enemy's health is %d. The Enemy is %s." % (EnemyHealth, EnemyIs))
# output = "The Enemy's health is 0. The Enemy is dead."
这是python中所有字符串的内置方法,可让您轻松地{}
用任何变量替换python字符串中的placehoder 。与上面的解决方案编号3不同,此format()
方法不需要您将不同的数据类型表示或转换为字符串,因为它将自动为您执行此操作。例如,要使打印语句正常工作,您可以执行以下操作:
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))
# output = "The Enemy's health is 0. The Enemy is dead."
从python 3.6开始,您现在还可以使用f字符串来替换字符串中的变量。此方法类似于上述.format()
方法,并且我认为是对该str.format()
方法的更好升级。要使用此方法,您所要做的就是f
在定义字符串时在开引号前声明状态,然后在字符串内使用格式{[variable name goes here]}
来使其起作用。例如,要使打印语句正常工作,请使用以下方法:
print(f"The Enemy's health is {EnemyHealth}. The Enemy is {EnemyIs}.")
# output = "The Enemy's health is 0. The Enemy is dead."
如您所见,通过使用此方法,variable name
可以直接在花括号内实例化{}
。