嘿,我只是想知道为什么在这段代码中:
def change_letter(line, what_letter_to_replace, what_to_replace_with):
"""
This function takes 3 parameters: a string, the letter that is going to be
replaced,
and what it is going to be replaced with.
"""
lst_line = list(line)
for letter in lst_line:
if letter == str(what_letter_to_replace):
lst_line[lst_line.index(letter)] = str(what_to_replace_with)
x = ''.join(lst_line)
y= x.split()
return y
该函数按预期工作,并返回新更新行中的单词列表,而在这段代码中:
def change_letter(line, what_letter_to_replace, what_to_replace_with):
"""
This function takes 3 parameters: a string, the letter that is going to be
replaced,
and what it is going to be replaced with.
"""
lst_line = list(line)
for letter in lst_line:
if letter == str(what_letter_to_replace):
lst_line[lst_line.index(letter)] = str(what_to_replace_with)
''.join(lst_line)
lst_line.split()
return lst_line
该函数有一个运行时AttributeError,表示' list'对象没有属性' split',但是由于前一行代码已经使lst_line已经成为字符串了吗?
答案 0 :(得分:3)
''.join(lst_line)
不会影响lst_line
。它返回 new 字符串。如果您希望将新字符串称为lst_line
,则需要将其分配回该变量:
lst_line = ''.join(lst_line)
请注意,这是第一个示例(它只是将其称为x
而不是lst_line
)。