Python错误:如何在不将其制成字符串的情况下打印存储为变量的数字?

时间:2018-08-06 23:46:17

标签: python string variables numbers

我正在创建一个练习程序,该程序显示角色名称及其年龄。由于某种原因,每当我存储字符的年龄而不用引号引起来时,该字符都不会打印。

我在视频中看到,将数字存储为变量时,不需要在其周围加上引号。大家好,请检查我的代码,让我知道我需要更改或添加的内容。

for my $aref (@complex) {
    for my $href (@$aref) {
        for (keys %{$href}) {
            print "$href->{$_}\n";
        }
    }
}

TypeError:只能将str(而不是“ int”)连接到str

3 个答案:

答案 0 :(得分:4)

有很多解决方案:

  • 将数字作为单独的参数传递给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.")
    

答案 1 :(得分:0)

最好的方法是在字符串中使用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 :(得分:-1)

对于python <2.7和3,您可以使用:

#!/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}。