如何从字符串列表中删除 \n

How to remove the \n from a list of strings

我正在尝试创建一个前往列表中位置的海龟,但我在执行此操作时遇到了问题,因为我的列表在每个位置之后包含一个“\n”。我尝试浏览列表并通过将 \n 从原始列表中删除为另一个没有 \n 的列表来更改每个列表。

我尝试了 lists.strip("\n"),但它似乎对我不起作用。

def gotoprocess():

    with open("one.txt", "r") as rp:
        print(rp.readlines())

        lists = rp.readlines()

        while True:
            for i in range(len(lists)):
                lists[i]

                if lists[i] == lists[-2]:
                    break
        print(lists)

我期待一个看起来像这样的列表

['(-300.00,300.00)','(-200.00,200.00)']

但有更多的数字。 我得到的是这个

['(-300.00,300.00)\n', '(-200.00,200.00)\n', '(-100.00,300.00)\n', '(-100.00,100.00)\n', '(-300.00,100.00)\n', '(-300.00,300.00)\n', '(-200.00,200.00)\n']

strip("\n") 应该有效。
但你可能错了两件事:

  1. strip()是字符串方法,应该作用于字符串元素(lists[i].strip("\n")),而不是列表(lists.strip("\n"))
  2. strip() returns复制修改后的字符串,不修改原字符串

您可以做的是使用剥离的字符串创建一个新列表:

lists = ['(-300.00,300.00)\n','(-200.00,200.00)\n', '(-100.00,300.00)\n','(-100.00,100.00)\n', '(-300.00,100.00)\n','(-300.00,300.00)\n', '(-200.00,200.00)\n']
locs = []

for i in range(len(lists)):
    locs.append(lists[i].strip("\n"))

print(locs)
# ['(-300.00,300.00)', '(-200.00,200.00)', '(-100.00,300.00)', '(-100.00,100.00)', '(-300.00,100.00)', '(-300.00,300.00)', '(-200.00,200.00)']

您可以使用列表理解进一步简化循环:

locs = [loc.strip("\n") for loc in lists]

print(locs)
# ['(-300.00,300.00)', '(-200.00,200.00)', '(-100.00,300.00)', '(-100.00,100.00)', '(-300.00,100.00)', '(-300.00,300.00)', '(-200.00,200.00)']