【问题标题】:"str = str.replace("something", "something_else")" not working in Python 3.6.5“str = str.replace("something", "something_else")" 在 Python 3.6.5 中不起作用
【发布时间】:2019-08-24 10:32:28
【问题描述】:

当我输入以下内容时:

str = str.replace("something", "something_else")

它返回:

AttributeError: 'tuple' object has no attribute 'replace'

我使用的是 Python 3.6.5。任何帮助将不胜感激。

【问题讨论】:

  • 你的变量str 是一个元组,而不是一个字符串。
  • 另外,str 是一个不好选择的变量名称,因为 str 内置类型已经在使用该名称。
  • 您是否要在字符串元组中用“something_else”替换所有出现的“something”?
  • 请发布您的整个代码,而不是没有上下文的单行代码。

标签: python


【解决方案1】:

查看str的内容。它包含一个元组,而不是一个字符串。是.split() 操作的输出还是类似的?

例如:

>>> str = ( 'a', 'b', 'banana' )
>>> str.replace("something", "something_else")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'replace'

显然它确实与正确的str一起工作:

>>> str = 'banana' 
>>> str.replace("something", "something_else")
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2018-08-14
    • 2018-01-25
    • 2021-12-05
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    相关资源
    最近更新 更多