简体   繁体   中英

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?

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?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM