fox
fox

Reputation: 16506

how do I parse a specific string in python

have a yaml file open to read

looking for a path that is stored in it

will always be on the second line of the file in the form

Location: !!python/unicode '[PATH here]'

sorry if this is elementary (I'm sure it is), but what's the easiest way to grab the path location?

Upvotes: 0

Views: 83

Answers (2)

Cameron Sparr
Cameron Sparr

Reputation: 3981

Another way, which will only work if you know the path will be the third element on the line:

line.split()[2]

or if you just know it will be the LAST element on the line:

line.split()[-1]

Upvotes: 0

abarnert
abarnert

Reputation: 365717

The quickest way is to just substring it:

line[28:-1]

But this only works if you're absolutely sure the line will be in exactly that format—no differences in whitespace, etc. And of course you have to be sure you've got the right line; if line 2 is a comment and line 3 is the real line, and you try to parse the comment with this, you'll get the right part of the comment and think it's a path.

A more robust and flexible solution might be to use a regexp:

re.match(r".* '(.*)'", line).group(1)

or:

re.match(r"Location:\s!!python/unicode\s'(.*)'", q).group(1)

… etc. Exactly what you want to use depends on what variation you want to allow, and what you want to guard against.

But really, if you want to parse YAML, why not just use a YAML parser?

Upvotes: 1

Related Questions