【问题标题】:please solve this TypeError: can only concatenate str (not "int") to str请解决这个 TypeError: can only concatenate str (not "int") to str
【发布时间】:2021-08-18 18:00:51
【问题描述】:
class traveler:
    def __init__(t,id,name,age,gender):
        t.id = id
        t.name = name
        t.age = age
        t.gender = gender

def myfunc(printinfo):
    print("Traveler ID is: " + printinfo.id)
    print("Traveler name is: " + printinfo.name)
    print("Traveler age is: " + printinfo.age)
    print("Traveler gender is: " + printinfo.gender)

t1 = traveler(1,"abc",20,"female")
t1.myfunc()


    

【问题讨论】:

  • str(printinfo.age)你的年龄是一个数字。所以不能连接到字符串。
  • 最好使用 f string : print(f"Traveler age is: {printinfo.age}") 而不是像那样写。
  • @Shamal_Shine :为什么用 shell 标记?
  • 非常感谢:)
  • @user1934428 初学者有时会过度使用标签。我删除了不相关的 shellclass 和 'python-idle`,并添加了 string,因为这是 TypeError 的主题。

标签: python class typeerror


【解决方案1】:

只需要在打印语句中使用string

def myfunc(printinfo):
    print("Traveler ID is: " + str(printinfo.id))
    print("Traveler name is: " + str(printinfo.name))
    print("Traveler age is: " + str(printinfo.age))
    print("Traveler gender is: " + str(printinfo.gender))

【讨论】:

  • 希望对您有所帮助.. 我也很享受学习之旅
【解决方案2】:

是一个简单的TypeError,你不能在打印函数中用+连接不同的类型。

我相信您可以轻松地在网上找到解决方案。

无论如何,尝试使用这个:

def myfunc(printinfo):
    print(f"Traveler ID is: {printinfo.id}")
    print(f"Traveler name is: {printinfo.name}")
    # etc...

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 2023-02-25
    • 2020-11-21
    • 2020-09-18
    • 1970-01-01
    • 2021-12-18
    • 2019-02-02
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多