Home > Net >  Is there an function to get a string between chars?
Is there an function to get a string between chars?

Time:12-28

input = "{1} {John Travis} {was} {here}"

Let's suppose that I want to get strings that are inside of the second and the third pair of brackets. So the expected output is:

output = "John Travis was"

I tried to use array split with spaces as a separator, expecting as result something like:

array = ["{1}", "{John Travis}", "{was}", "{here}"]

array[1] = re.sub("{", "", array[1])
array[1] = re.sub("}", "", array[1])

array[2] = re.sub("{", "", array[2])
array[2] = re.sub("}", "", array[2])

#expected result: array[1]   array[2] ( "John Travis was" )

But I remembered that I have the separator " " on 'John Travis', resulting:


array = ["{1}", "{John", "Travis}", "{was}", "{here}"]

array[1] = re.sub("{", "", array[1])
array[2] = re.sub("}", "", array[2])

array = ["{1}", "John", "Travis", "{was}", "{here}"]

#unexpected result: array[1]   array[2] ( "John Travis" )

How to proceed?

Thanks for listening.

CodePudding user response:

for the desired output you can use regex:

import re

input = "{1} {John Travis} {was} {here}"

# Use a regular expression to match the pattern of the brackets and the content inside them
matches = re.findall(r'\{([^}]*)\}', input)

# Extract the second and third items in the list of matches
output = matches[1]   ' '   matches[2]

print(output)  

output would be:

John Travis was

CodePudding user response:

Another solution (without re), you can replace { with ' and } with ', and then use ast.literal_eval to evaluate string as a tuple. Then you can use standard indexing:

from ast import literal_eval

s = "{1} {John Travis} {was} {here}"

s = literal_eval(s.replace("{", "'").replace("}", "',"))
print(s[1], s[2])

Prints:

John Travis was

CodePudding user response:

Alternate workaround with list comprehension:

input = "{1} {John Travis} {was} {here}"
print(*[i.strip('{}') for i in input.split()[1:-1]])

# John Travis was
  • Related