1

I have a file such that each line consists of two strings separated by variable space, like below:

"Doe, Mary" "W 135"

How can this be parsed into pairs of strings, ["Doe, Mary", "W 135"]?

20
  • 1
    @sashkello: That won't help for this problem, because str.split won't distinguish between spaces within the quotes and spaces between the quoted strings. Commented Sep 25, 2013 at 1:27
  • 2
    @abarnert I agree that the csv module is a better solution, but stripping off the quotes is not a problem. In fact, [s for s in '"Doe, Mary" "W 135"'.split('"') if s.strip()] ought to work unless one of the lines is like "foo" " "\n Commented Sep 25, 2013 at 1:33
  • 1
    @sashkello: No, it can't be done easily. str.split can't split on variable-length patterns (except for the special case of "any range of whitespace"). And there's now way it can distinguish quotes unless they're part of the split pattern. So, the only way you could possibly do it with str.split is to first split on words, then group by quotes, then re-join each group, which is far from easy. (@sashkello: Of course re.split is another story—it can split on variable-length patterns, which solves the problem with str.split immediately.) Commented Sep 25, 2013 at 1:41
  • 1
    Also, the fact that two pretty clever people went through a number of different attempts that they were confident would work, but they didn't, kind of proves that it's not easy… Commented Sep 25, 2013 at 1:44
  • 1
    @sashkello: Again, not done. Try it on "Doe Two-Space Mary" "W 135" and see what you get. Are you deliberately trying to prove my point here? Commented Sep 25, 2013 at 2:02

1 Answer 1

2
with open('file.txt') as f:
    pairs = csv.reader(f, delimiter=' ', skipinitialspace=True)

Now you can make a list of pairs, iterate over it in a for loop, whatever.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.