1

I have a multi-line string which looks like this:

something1
something2
something3

I'm wanting to send each line of this string to a list so that result[0] = something1 and so on.

I have tried doing this:

for line in tableOut:
        results.append(line.strip().split('\n'))

However, this makes every character of the string sent to a unique index in the list.

For example:

[['s'], ['o'], ['m'], ['e'], ['t'], ['h'], ['i'], ['n'], ['g'], ['1']]

Why isn't this working, and how can I send each line of a multi line string to a unique index in a list within a for loop?

jkdev
  • 11,360
  • 15
  • 54
  • 77
john doe
  • 170
  • 1
  • 11
  • Look at the string function `split()` To get a list of lines then the `for x in y` operation on list y will assign each entry in y to x - but be careful to make sure that the resulting lines are clean of \r or \n etc. So perhaps use `strip()` on the results of split – DisappointedByUnaccountableMod Oct 03 '19 at 16:15
  • 3
    `[x_ for x_ in [x.strip() for x in data.splitlines()] if x_]`. The fixed version of your code could be `for line in tableOut.split('\n'): results.append(line.strip())`. – sardok Oct 03 '19 at 16:15
  • `tableOut.split()`. (Iterating through a string yields the characters.) – Alan Oct 03 '19 at 16:16
  • 2
    `results = tableOut.splitlines()`? – pault Oct 03 '19 at 16:20

2 Answers2

3

tableOut is a string: a sequence of characters. Naming your loop index line is misleading, as the iterator over a string returns individual characters. That's your major problem.

Instead, split your string into a list of lines -- as @sardok has already summarized. Strip the individual lines. You can do this with a list comprehension isntead of an explicit loop.

results = [strip(line) for line in tableOut.split('\n')]
Prune
  • 76,765
  • 14
  • 60
  • 81
0

It's not clear what you meant by "multi-line" string but lets say it's something like this:

tableOut = 'something1\n' \
           'something2\n' \
           'something3'

Then you could do:

result = []
for line in tableOut.split('\n'):
    result.append(line.strip())

Not the most pythonic way, but it's similar to what you were trying to do.

Rafael
  • 1
  • 2