If you combine the string and the value as they are in Python, an error will occur.
str_int.py
NAME="Taro"
AGE=15
print(NAME + " is " + AGE + " years old")
An error occurred because the string and value cannot be combined as they are.
output
Traceback (most recent call last):
File "str_int.py", line 5, in <module>
print(NAME + " is " + AGE + " years old")
TypeError: can only concatenate str (not "int") to str
There are various solutions. Personally, I like 2 because it looks like programming. If you write only the points 1: Convert the value (AGE) to a string using str () 2:% s = character string,% d = value, so if you do not write this correctly, an error will occur 4: If you forget the leading "f", the variable name string will be output as it is without the variable being assigned. 5: If you connect with ",", a space will be automatically inserted and you will not need to use str (). <2019/12/22: Item 5 added due to konandoiruasa's point>
str_int2.py
NAME="Taro"
AGE=15
print("1 : " + NAME + " is " + str(AGE) + " years old")
print("2 : %s is %d years old" % (NAME, AGE))
print("3 : {} is {} years old".format(NAME, AGE))
print(f"4 : {NAME} is {AGE} years old")
print("5 :", NAME, "is", AGE, "years old")
Everything went well. Taro is 15 years old.
output
1 : Taro is 15 years old
2 : Taro is 15 years old
3 : Taro is 15 years old
4 : Taro is 15 years old
5 : Taro is 15 years old
Recommended Posts