JavierG
JavierG

Reputation: 212

Matching substring in pattern in Python

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?

Upvotes: 0

Views: 198

Answers (3)

Krcn U
Krcn U

Reputation: 421

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]

Upvotes: 1

Martin Evans
Martin Evans

Reputation: 46779

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.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174836

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]

Upvotes: 1

Related Questions