使用列表综合重新创建strip()方法,但输出返回意外结果



为了好玩,我正试图在python中"重新创建"str.split()方法。

def ourveryownstrip(string, character):
newString = [n for n in string if n != character]
return newString
print("The string is", ourveryownstrip(input("Enter a string.`n"), input("enter character to remove`n")))

它的工作方式是,我创建了一个传递两个参数的函数:1(第一个参数是提供的字符串,2(第二个参数是一个字符串或字符,用户希望将其从字符串中移出/空白。然后,我使用列表理解,通过使用条件语句将"修改"的字符串存储为新列表。然后,它将修改后的字符串作为列表返回。

然而,输出将整个内容作为一个数组返回,字符串中的每个字符都用逗号分隔。

预期输出:

Boeing 747 Boeing 787
enter character to removeBoeing
The string is ['B', 'o', 'e', 'i', 'n', 'g', ' ', '7', '4', '7', ' ', 'B', 'o', 'e', 'i', 'n', 'g', ' ', '7', '8', '7']

我该怎么解决这个问题?

您所设置的是检查列表中的每个单独字符,看看它是否与"Boeing"匹配,这永远不会是真的,因此它将始终返回整个输入。它将其作为列表返回,因为使用列表理解可以生成列表。就像@BrutusForcus说的那样,这可以通过字符串切片和string.index()函数来解决:

def ourveryownstrip(string,character):
while character in string:
string = string[:string.index(character)] + string[string.index(character)+len(character):]
return string

这将首先检查要删除的值是否在字符串中。如果是,则string[:string.index(character)]将在character变量值的第一次出现之前获得所有字符串,而string[string.index(character)+len(character):]将在变量值的首次出现之后获得字符串中的所有字符串。这种情况将一直发生,直到变量值不再出现在字符串中。

最新更新