【问题标题】:String concatenation fails字符串连接失败
【发布时间】:2017-11-24 03:07:12
【问题描述】:

我正在学习python,在这里遇到了一些新问题。谁能解释这段python代码内部到底发生了什么。

>>> s="sam"
>>> s +="dam"
>>> s
'samdam'
>>> d +=s
>>> d
'msamdam'
>>> f = f+s

Traceback (most recent call last):
  File "<pyshell#129>", line 1, in <module>
    f = f+s
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> f +=s

Traceback (most recent call last):
  File "<pyshell#130>", line 1, in <module>
    f +=s
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

【问题讨论】:

  • 你的代码中的 f 是什么?
  • 您能否更新您的代码以包含 d 和 f 的实例?

标签: python string concatenation


【解决方案1】:

我可以假设变量 f 是整数类型,s 是字符串。您不能以这种方式连接整数和字符串。如果你想这样做,它应该是这样的:

str(f) + s

【讨论】:

    【解决方案2】:

    这里的 f 好像是一个整数,所以也许你可以使用:

    f = str(f) + s
    

    这样,f就会变成一个字符串了。

    【讨论】:

      【解决方案3】:

      fintegersstring。您不能连接数字和字符串。

      您可以这样做:

      x = str(f) + s
      

      这会将f 转换为字符串,然后与s 连接。例如,如果f123,则x 将是123msamdam

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-02
        • 2011-02-07
        • 1970-01-01
        相关资源
        最近更新 更多