简体   繁体   中英

Python Parseing String by Single Quotes

I am trying to Parse the following string:

EDITED to account for spaces...

['THE LOCATION', 'THE NAME', 'THE JOB', 'THE AREA')]

Right now I use regular expressions and split the data with the comma into a list

InfoL = re.split(",", Info)

However my output is

'THE LOCATION'
'THE NAME'
'THE JOB'
'THE AREA')]

Looking to have the output as follows

THE LOCATION
THE NAME
THE JOB
THE AREA

Thoughts?

One possibility is to use strip() to remove the unwanted characters:

In [18]: s="['LOCATION', 'NAME', 'JOB', 'AREA')]"

In [19]: print '\n'.join(tok.strip("[]()' ") for tok in s.split(','))
LOCATION
NAME
JOB
AREA

Like your original solution, this will break if any of strings are allowed to contain commas.

PS If that closing parenthesis in your example is a typo, you might be able to use ast.literal_eval() :

In [22]: print '\n'.join(ast.literal_eval(s))
LOCATION
NAME
JOB
AREA
InfoL = re.split("[, '()\[\]]*", Info)

try this code snippet :

import re
tmpS = "['THE LOCATION', 'THE NAME', 'THE JOB', 'THE AREA')]"
tmpS = re.sub('[^\w\s,]+', '', tmpS)
print tmpS # Result -> 'THE LOCATION, THE NAME, THE JOB, THE AREA'
for s in tmpS.split(','):
     print s.strip()


O/P:
THE LOCATION
THE NAME
THE JOB
THE AREA

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