Saurav Rai
Saurav Rai

Reputation: 2347

Finding sub-strings between two characters

I want (202, 233) and (286, 298) from the following string as separate two substrings.

x = "[977, 1, 0, (202, 233), (286, 298)]"

What I tried till now is given below

char1 = '('
char2 = ')'
substr1 = x[x.find(char1) : x.find(char2)]

It gives me output as (202, 23 which is not the same as required. Also I am not able to find the second substring using this way.

Any help is appreciated.

Upvotes: 0

Views: 76

Answers (5)

Wan
Wan

Reputation: 26

you can use the following.

import re
print(re.findall('\(.*?\)', x))

Upvotes: 1

Swati Srivastava
Swati Srivastava

Reputation: 1157

A very naive approach to this problem (without regex) is

start = -1
end = -1
ans = []
for i in range(len(x)):
    if x[i] == '(':
        start = i
    elif x[i] == ')':
        end = i
    if (start != -1 and end != -1):
        s = x[start:end + 1]
        if not s in ans and s != '':
            ans.append(s)

The above approach is string based. It extracts the substring from '(' index to ')' index.

A better approach than this is

x = eval(x)
for i in x:
    if type(i) is tuple:
        print (i)

Upvotes: 0

rajeshkumargp
rajeshkumargp

Reputation: 105

Input is String:

    x = "[977, 1, 0, (202, 233), (286, 298)]"

Output Expected:

   (202, 233), (286, 298)

Using ast.literal_eval, the string can be made as Python List. After converting it to a pythonic object, inspection on datatype can be done to isolate tuples.

Trial:

    x_as_string = """[977, 1, 0, (202, 233), (286, 298)]"""
    x_as_list = ast.literal_eval(x_as_string)

    expected_output = []

    for i in x_as_list:
        if isinstance(i,tuple):
            expected_output.append(i)

    print(str(expected_output))
    print(''.join([str(e) for e in expected_output]))

Reference : Convert string representation of list to list

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

Use:

import re
print(re.findall('\(.*?\)', x))

Or use:

import ast
print([str(i) for i in ast.literal_eval(x) if isinstance(i, tuple)])    

Both output:

['(202, 233)', '(286, 298)']

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521499

Assuming you don't have to worry about nested parentheses, you could try using re.findall here:

inp = "x = [977, 1, 0, (202, 233), (286, 298)]"
matches = re.findall(r'\(.*?\)', inp)
print(matches)

This prints:

['(202, 233)', '(286, 298)']

Upvotes: 3

Related Questions