【问题标题】:How to remove the \n from a list of strings [duplicate]如何从字符串列表中删除 \n [重复]
【发布时间】:2019-06-01 16:05:54
【问题描述】:

我正在尝试创建一个前往列表中位置的海龟,但我在执行此操作时遇到了麻烦,因为我的列表在每个位置之后都包含一个“\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']

【问题讨论】:

  • 你想在while循环和if条件中做什么?

标签: python python-3.x list newline


【解决方案1】:

strip("\n") 应该可以工作。
但你可能搞错了两件事:

  1. strip() 是一个字符串方法,它应该应用于字符串元素 (lists[i].strip("\n")),而不是列表 (lists.strip("\n"))
  2. strip() 返回修改后字符串的副本,不修改原字符串

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

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)']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 2014-08-02
    • 2014-02-15
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    相关资源
    最近更新 更多