0

I am trying to use enumerate() on a string already in memory (thus not from file), which string has comma separated values (or space, but uniformly, i.e. not mix of comma and spaces). Basically I just want to get the whole line n, something quite similar to the first part of this question.

If I do a print on my string (before entering the function), it shows something like this:

89,abc,def01,ghi23
01,jkl,mno45,pqr67

however this code does not work, presumably because my lines are not individually surrounded by quotes:

def pickline(thestring, whatline):
  for i, line in enumerate(thestring):
    if i == whatline:
      return line

Question: what should I do to get this right ?

edit The expected output should be:

# string
89,abc,def01,ghi23
# if whatline value is 0,
# or string
01,jkl,mno45,pqr67
# if whatline value is 1,
# etc.
Community
  • 1
  • 1
secarica
  • 597
  • 5
  • 18
  • 3
    What is your expected output? – thefourtheye Apr 27 '14 at 13:24
  • 1
    iterating a string goes character-by-character. Quotes have nothing at all to do with it. If you need to iterate over the chunks between commas, use `.split(",")` or the `csv` module. – Wooble Apr 27 '14 at 13:26
  • Does your string contain newlines, or are the two lines of your example input from two different strings? – John Zwinck Apr 27 '14 at 13:26
  • Printing on screen goes line by line, so I assumed it ends with \n, but I checked anyway: I wrote the raw string to a file and inside the file the lines are separated by 0x0D and 0x0A; I am on Windows and don't know if the OS intervenes when saving a raw text, I suppose not (?). – secarica Apr 27 '14 at 15:18
  • @thefourtheye Sorry, I thought it was clear enough saying "I just want to get the whole line n", but I get the point, will do more clearly in the future, as in the **edit** above (hopefully). – secarica Apr 27 '14 at 15:22

1 Answers1

1

You have to split the string into lines first.

for i, line in enumerate(thestring.splitlines()):

However, a better way to do this is to do this:

def pickline(thestring, whatline):
    return thestring.splitlines()[whatline]
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251