为什么 string.strip() 函数在某些单词中删除了我想要的字符,而在其他单词中删除了 none
why do string.strip() function removed the character i want in some words and remove none in others
我正在尝试删除字符串中的“\n”字符,因为当我从文件中读取行时,它包含“\n”字符!!
输入:
with open('names.txt', mode='r') as file:
list_of_names = file.readlines()
print(list_of_names)
for name in list_of_names:
list_of_names.remove(name)
name = name.strip('\n')
list_of_names.append(name)
print(list_of_names)
输出:
['Aang\n', 'Zuko\n', 'Appa\n', 'Katara\n', 'Sokka\n', 'Momo\n', 'Uncle Iroh\n', 'Toph']
['Zuko\n', 'Katara\n', 'Momo\n', 'Toph', 'Appa', 'Uncle Iroh', 'Sokka', 'Aang']
因为您在迭代列表的同时修改列表,所以在循环进行到一半时,list_of_names.remove(name)
试图删除错误的元素。这也是列表顺序发生变化的原因。这不必要地复杂。
与其修改旧列表,不如考虑简单地附加到一个新的空列表。
with open('names.txt', mode='r') as f:
list_of_names = f.readlines()
new_list_of_names = []
print(list_of_names)
for name in list_of_names:
name = name.strip('\n')
new_list_of_names.append(name)
print(new_list_of_names)
或者,对于更短的代码,使用 list comprehension:
with open('names.txt') as f:
list_of_names = f.readlines()
new_list_of_names = [name.strip('\n') for name in list_of_names]
print(list_of_names)
print(new_list_of_names)
(注意:mode='r'
是多余的,因为默认模式是读取。)
我正在尝试删除字符串中的“\n”字符,因为当我从文件中读取行时,它包含“\n”字符!! 输入:
with open('names.txt', mode='r') as file:
list_of_names = file.readlines()
print(list_of_names)
for name in list_of_names:
list_of_names.remove(name)
name = name.strip('\n')
list_of_names.append(name)
print(list_of_names)
输出:
['Aang\n', 'Zuko\n', 'Appa\n', 'Katara\n', 'Sokka\n', 'Momo\n', 'Uncle Iroh\n', 'Toph']
['Zuko\n', 'Katara\n', 'Momo\n', 'Toph', 'Appa', 'Uncle Iroh', 'Sokka', 'Aang']
因为您在迭代列表的同时修改列表,所以在循环进行到一半时,list_of_names.remove(name)
试图删除错误的元素。这也是列表顺序发生变化的原因。这不必要地复杂。
与其修改旧列表,不如考虑简单地附加到一个新的空列表。
with open('names.txt', mode='r') as f:
list_of_names = f.readlines()
new_list_of_names = []
print(list_of_names)
for name in list_of_names:
name = name.strip('\n')
new_list_of_names.append(name)
print(new_list_of_names)
或者,对于更短的代码,使用 list comprehension:
with open('names.txt') as f:
list_of_names = f.readlines()
new_list_of_names = [name.strip('\n') for name in list_of_names]
print(list_of_names)
print(new_list_of_names)
(注意:mode='r'
是多余的,因为默认模式是读取。)