为什么string.strip()函数删除了我想要的字符

发布于 2025-01-21 20:47:14 字数 547 浏览 3 评论 0原文

我正在尝试将“ \ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゝ杯具 2025-01-28 20:47:14

因为您在迭代时修改了列表,所以循环中途进行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 list classension classension

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'是多余的,因为读取了默认模式。

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.

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)

Or, for shorter code, use 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)

(Note: mode='r' is redundant because the default mode is read.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文