【问题标题】:TypeError: Can't convert 'int' object to str implicitly [duplicate]TypeError:无法将'int'对象隐式转换为str [重复]
【发布时间】:2015-03-23 02:33:29
【问题描述】:

我是新手。我已经开始在 Ubuntu 上使用 python。我的版本是 Python3.4 我写了以下代码并得到了错误:

>>> g=input("Enter number here: ")
Enter number here: 43
>>> g+7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> a= input("Enter:")
Enter:43
>>> a +32
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> a+32
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> 

有什么可以帮忙的吗?

【问题讨论】:

标签: python


【解决方案1】:

也许你可以试试这个...
在 python 3.4 中,input() 被转换为字符串。你可以打电话给g,结果是'43'..这个字符串..
所以转换成integer

>>> g=input("Enter number here: ")
Enter number here: 43
>>> g+7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> 
>>> g
'43'
>>> int(g)+7
50
>>>

【讨论】:

    【解决方案2】:

    试试:

    >>> int(g)+7
    

    ...和:

    >>> int(a) + 32
    

    【讨论】:

      【解决方案3】:

      input 将返回一个str,您必须将其转换为int 才能对其进行数值运算

      >>> g = int(input('enter a number:'))
      enter a number: 5
      
      >>> g + 7
      12
      

      转化前

      >>> g = input('enter a number:')
      enter a number: 5
      
      >>> type(g)
      <class 'str'>
      

      转换后

      >>> g = int(input('enter a number:'))
      enter a number: 5
      
      >>> type(g)
      <class 'int'>
      

      【讨论】:

        猜你喜欢
        • 2012-11-19
        • 1970-01-01
        • 2013-09-27
        • 1970-01-01
        • 1970-01-01
        • 2017-07-21
        • 1970-01-01
        • 2017-03-27
        相关资源
        最近更新 更多