我正在创建一个练习程序,显示角色的姓名及其年龄。由于某种原因,每当我存储角色的年龄而不用引号引起来时,它就不会打印。
我在视频中看到,将数字存储为变量时,不需要在其周围加上引号。你们可以检查一下我的代码,让我知道我需要更改或添加什么吗?
character_name = "Tyrone"
character_age = 22
print("There was once a man named " + character_name + ",")
print("he was " + character_age + " years old.")
print("He really liked the name " + character_name + ",")
print("but didn't like being " + character_age + ".")
TypeError:只能将 str(不是“int”)连接到 str
解决方案有很多:
将数字作为单独的参数传递给
print()
- print()
函数可以采用多个参数:
print("he was", character_age, "years old.")
使用格式创建一个包含数字的字符串:
print("he was %s years old." % character_age)
print("he was {} years old.".format(character_age))
print(f"he was {character_age} years old.")
在连接之前将数字转换为字符串:
print("he was " + str(character_age) + " years old.")
最好的方法是在字符串中使用
format()
和符号 {}
。
它也更便携,可以处理各种对象,包括数字和字符串。
而且更清晰了,你的短信完全保留在那里,看看那个!
print("There was once a man named {},".format(character_name))
print("he was {} years old.".format(character_age))
print("He really liked the name {},".format(character_name))
print("but didn't like being {}.".format(character_age))
对于蟒蛇<2.7 and 3 you can use:
#!/bin/env python
character_name = "Tyrone"
character_age = 22
print("There was once a man named " + character_name + ",")
print("he was {0}".format(character_age) + " years old.")
print("He really liked the name " + character_name + ",")
print("but didn't like being {0}".format(character_age) + ".")
对于 python >2.7,您可以排除位置限定符 - {} 而不是 {0} 也可以。