【问题标题】:TypeError: 'str' object does not support item assignment (Python)TypeError:“str”对象不支持项目分配(Python)
【发布时间】:2015-09-16 19:23:39
【问题描述】:

这就是我想要做的:

输入:ABCDEFG

期望的输出:

***DEFG
A***EFG
AB***FG
ABC***G
ABCD***

这是我写的代码:

def loop(input):
    output = input
    for index in range(0, len(input)-3):              #column length
        output[index:index +2] = '***'
        output[:index] = input[:index]
        output[index+4:] = input[index+4:]
        print output + '\n'

但我得到了错误:TypeError: 'str' object does not support item assignment

【问题讨论】:

  • 字符串是不可变的。如果要更改它,请将其转换为列表,操作列表,然后将其连接回字符串。
  • 我该怎么做?
  • 这不是你的问题,而是input 是 Python 中的内置函数,最好不要用变量覆盖它。

标签: python


【解决方案1】:

您不能修改字符串的内容,您只能使用更改创建一个新字符串。因此,您需要这样的功能,而不是上面的功能

def loop(input):
    for index in range(0, len(input)-3):              #column length
        output = input[:index] + '***' + input[index+4:]
        print output

【讨论】:

    【解决方案2】:

    字符串是不可变的。您不能更改字符串中的字符,但必须创建一个新字符串。如果要使用项目分配,可以将其转换为列表,操作列表,然后将其连接回字符串。

    def loop(s):
        for index in range(0, len(s) - 2):
            output = list(s)                    # create list from string
            output[index:index+3] = list('***') # replace sublist
            print(''.join(output))              # join list to string and print
    

    或者,只需从旧字符串的切片与'***' 结合创建一个新字符串:

            output = s[:index] + "***" + s[index+3:] # create new string directly
            print(output)                            # print string
    

    另请注意,您的代码中似乎存在一些错误,您不应使用 input 作为变量名,因为它会影响同名的内置函数。

    【讨论】:

      【解决方案3】:

      在 Python 中,字符串是不可变的——一旦创建就无法更改。这意味着与列表不同,您不能分配给索引来更改字符串。

      string = "Hello World"
      string[0] # => "H" - getting is OK
      string[0] = "J" # !!! ERROR !!! Can't assign to the string
      

      在你的情况下,我会将output 设为一个列表:output = list(input),然后在你完成后将其转回一个字符串:return "".join(output)

      【讨论】:

        【解决方案4】:

        在 python 中,您不能将值分配给字符串数组中的特定索引,您可能希望将值连接起来。比如:

        for index in range(0, len(input)-3):
            output = input[:index]
            output += "***"
            output += input[index+4:]
        

        不过,您会想要注意边界。现在循环结束时 index+4 会太大而导致错误。

        【讨论】:

        • output = input[:input] 应该是output = input[:index]
        【解决方案5】:

        字符串是不可变的,所以不支持像列表那样的赋值,你可以使用str.join连接你的字符串切片一起创建一个新的字符串每次迭代:

        def loop(inp):
            return "\n".join([inp[:i]+"***"+inp[i+3:] for i in range(len(inp)-2)])
        

        inp[:i] 将获得第一个切片,第一次迭代将是一个空字符串,然后在每次迭代时在字符串中移动另一个字符,inp[i+3:] 将从当前索引 i 开始获得一个切片加上三个索引也一次在字符串中移动一个字符,然后您只需要将两个切片连接到您的 *** 字符串。

        In [3]: print(loop("ABCDEFG"))
        ***DEFG
        A***EFG
        AB***FG
        ABC***G
        ABCD***
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-22
          • 1970-01-01
          • 1970-01-01
          • 2021-02-16
          • 1970-01-01
          • 2016-05-12
          • 1970-01-01
          相关资源
          最近更新 更多