1

I am trying to create a turtle which goes to the locations on a list and I'm having trouble doing this because my list contains a "\n" after each position. I tried going through the list and changing each one by removing \n from the original to a different one without \n.

I tried lists.strip("\n") but it doesn't seem to work for me.

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)

I expected a list that looks like this

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

but with more numbers. What I got was this

['(-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']
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Mat
  • 203
  • 1
  • 2
  • 6

1 Answers1

1

The strip("\n") should work.
But you probably got 2 things wrong:

  1. strip() is a string method and it should be applied to the string elements (lists[i].strip("\n")), not on the list (lists.strip("\n"))
  2. strip() returns a copy of the modified string, it does not modify the original string

What you can do is to create a new list with the stripped strings:

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

You can further simplify the loop with list comprehension:

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)']
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135