“str”对象不支持项目分配(Python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38601139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:10:20  来源:igfitidea点击:

'str' object does not support item assignment (Python)

python

提问by user1072337

def remove_char(text):
    for letter in text[1]:
        text[0] = text[0].replace(letter," ")
    return text[0]

This is returning:

这是返回:

'str' object does not support item assignment

Why? And how can I make this work?

为什么?我怎样才能做到这一点?

回答by xgord

In Python, strings are not mutable, which means they cannot be changed. You can, however, replace the whole variable with the new version of the string.

在 Python 中,字符串是不可变的,这意味着它们不能被更改。但是,您可以用新版本的字符串替换整个变量。

Example:

例子:

text = ' ' + text[1:] # replaces first character with space

回答by Anthony Pham

Strings are immutable. By trying:

字符串是不可变的。通过尝试:

text[0] = text[0].replace(letter," ")

you are trying to access the string and change it, which is disallowed due to the string's immutability. Instead, you can use a forloop and some slicing:

您正在尝试访问字符串并更改它,由于字符串的不变性,这是不允许的。相反,您可以使用for循环和一些切片:

for i in range(0, len(y)):
    if y[i] == ",":
        print y[i+1:len(y)]
        break

You can change the string a variable is assigned to (second piece of code) rather than the string itself (your piece of code).

您可以更改分配给变量的字符串(第二段代码)而不是字符串本身(您的代码段)。

回答by Tonechas

Assuming that the parameter textis a string, the line for letter in text[1]:doesn't make much sense to me since text[1]is a single character. What's the point of iterating over a one-letter string?

假设参数text是一个字符串,该行for letter in text[1]:对我来说没有多大意义,因为它text[1]是一个字符。迭代一个字母的字符串有什么意义?

However, if textis a list of strings, then your function doesn't throw any exceptions, it simply returns the string that results from replacing in the first string (text[0]) all the letters of the second string (text[1]) by a blank space (" ").

但是,如果text是一个字符串列表,那么您的函数不会抛出任何异常,它只是返回在第一个text[0]字符串 ( text[1]) 中用空格 ( " ")替换第二个字符串 ( ) 的所有字母所产生的字符串。

The following examples show how remove_charworks when its argument is a list of strings:

下面的例子展示了remove_char当它的参数是一个字符串列表时是如何工作的:

In [462]: remove_char(['spam', 'parrot', 'eggs'])
Out[462]: 's  m'

In [463]: remove_char(['bar', 'baz', 'foo'])
Out[463]: '  r'

In [464]: remove_char(['CASE', 'sensitive'])
Out[464]: 'CASE'

Perhaps this is not the intended behaviour...

也许这不是预期的行为......