为什么string.strip()函数删除了我想要的字符
我正在尝试将“ \ 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']
i am trying to remove the '\n' characters a string because when i read the lines from a file it include the '\n' characters!!
input:
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)
output:
['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']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您在迭代时修改了列表,所以循环中途进行
list_of_names.remove(name)
试图删除错误的元素。这也是列表的顺序更改的原因。这是不必要的复杂。与其修改旧列表,不如考虑将附加附加到一个新的空列表中。
或者,对于较短的代码,请使用 list list classension classension
强>注意:
mode ='r'
是多余的,因为读取了默认模式。Because you are modifying the list while iterating over it, halfway through the loop,
list_of_names.remove(name)
is trying to remove the wrong element. This is also why the order of the list changes. This is unnecessarily complex.Instead of modifying the old list, consider simply appending to a new, empty list.
Or, for shorter code, use list comprehension:
(Note:
mode='r'
is redundant because the default mode is read.)