0

I'd like to get the substring s2 in this string pattern

 ('s1', 's2', 's3', 's4')

with s1, s2, s3 being any string (with variable length) and the commas, the blanks and the brackets are those specific chars. I wonder: is there a pythonic, simply way to do it using regex matching or similar?

2
  • 1
    ast.literal_eval(s)[1] Commented Aug 22, 2015 at 17:06
  • 1
    Are single quotes escaped in s1, s2, ...? Commented Aug 22, 2015 at 17:08

3 Answers 3

1

A regular expression as follows could be used:

import re

print re.findall("'(\w+)'", "('s1', 's2', 's3', 's4')")

Giving you a list of all of the entries as follows:

['s1', 's2', 's3', 's4']

So for s2:

print re.findall("'(\w+)'", "('s1', 's2', 's3', 's4')")[1]

As another alternative, the Python csv module could be used which deals quite well with various quoting scenarios:

import csv, StringIO

text = "('s1', 's2', 's3', 's4')"
print next(csv.reader(StringIO.StringIO(text.strip("()")), skipinitialspace=True, quotechar="'"))[1]

This first converts the text into a file type object which is needed using the csv reader.

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

Comments

1

You may get the answer through ast

import ast
h = "('s1', 's2', 's3', 's4')"
print ast.literal_eval(h)[1]

or

Through splitting.

print h.split(', ')[1]

or

print h.split("', '")[1]

Comments

1

straightforward with strip and split alltogether.

s="""('s1', 's2', 's3', 's4')"""
print s.split()[1].strip("',")

but regex is more clean:

import re
s="""('s1', 's2', 's3', 's4')"""
print re.findall("\w\d",s)[1]

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.