【问题标题】:AttributeError: 'function' object has no attribute 'replace'AttributeError: 'function' 对象没有属性 'replace'
【发布时间】:2014-06-19 00:22:40
【问题描述】:

我正在使用此代码尝试替换字符:

from another_test import test_once_more
test_once_more()
question = input("1 letter ")
for letter in question:
    if letter == "a":
        test_once_more.replace("1","a")
        print (test_once_more)

这是我正在使用的代码。我想做的就是替换这段代码中的1

def test_once_more():
    print ("123456789")

并将其替换为"A"

【问题讨论】:

    标签: python function object replace attributeerror


    【解决方案1】:

    这里有一个非常简单的错误; test_once_more 是您的函数的名称,而 question 是您的字符串的名称。试试question.replace(并修正另一个类似的错误)。

    附:字符串在 Python 中是不能变异的,所以需要将调用 replace 的结果赋值给另一个变量,才能看到调用 replace() 的效果。

    【讨论】:

      【解决方案2】:

      你不能。

      函数正在打印一些东西并返回None。事后没有办法改变它。

      应该做的是让函数返回一个值并处理那个

      def test_once_more():
          return "123456789"
      

      然后

      from another_test import test_once_more
      result = test_once_more()
      question = input("1 letter ")
      for letter in question:
          if letter == "a":
              result = result.replace("1","a")
              print (result)
      

      虽然我很困惑你为什么要使用 for 循环来迭代一个字符串,该字符串将是一个字符(至少如果你的用户遵循你的请求)......

      【讨论】:

      • 谢谢你的帮助 我在学校里学python的时候还不是很擅长
      猜你喜欢
      • 2014-09-02
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2019-08-02
      • 2016-03-10
      • 2022-01-26
      相关资源
      最近更新 更多