【问题标题】:'TypeError: can only concatenate tuple (not "str") to tuple' error [closed]'TypeError:只能将元组(不是“str”)连接到元组'错误[关闭]
【发布时间】:2020-04-11 21:37:26
【问题描述】:

我是 python 新手,我正在努力学习我编写了这段代码

weight = input('How much do you weigh in pounds? ')
weight_kg = int(weight)* 0,453592
print (weight_kg + 'is your weight is kilogrammes')

但是当我运行它时,我得到了这个错误

Traceback (most recent call last):
  File "C:/Users/hh/Desktop/PYTHON-LEARNING!/app.py", line 3, in <module>
    print (weight_kg + 'hi')
TypeError: can only concatenate tuple (not "str") to tuple

【问题讨论】:

  • 代码和回溯不匹配。
  • 你已经在weight_kg = ...,... 行创建了一个带有逗号的元组。要创建float 号码,请改用.
  • '0,453592',应该是'0.453592'
  • 在尝试连接字符串时,您还必须将其转换为 str:str(weight_kg) + '...'
  • 同样,一旦你完成了上述操作,你需要将weight_kg 转换为str,如果你想将它们连接在一起print (str(weight_kg) + ' is your weight is kilogrammes'),否则如果你不想隐式转换使用逗号而不是加号 print (weight_kg, 'is your weight is kilogrammes')

标签: python python-3.x string tuples typeerror


【解决方案1】:

这里有两个问题,一个是你乘以一个浮点数,用逗号作为小数分隔符,第二个是你不能在打印语句中连接一个浮点数和一个字符串。下面是固定代码 - 我使用 f-string 打印最终输出,这需要 Python 3.6。

weight = input('How much do you weigh in pounds? ')
weight_kg = int(weight)* 0.453592
print (f"{weight_kg} is your weight is kilogrammes")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多