1
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.

Álef
  • 13
  • 4
  • 1
    Did you consider `re.findall()` with a regexp that matches everything between `{` and `}`? – Barmar Dec 27 '22 at 23:50
  • Does this answer your question? [Regular expression to return all characters between two special characters](https://stackoverflow.com/questions/9889635/regular-expression-to-return-all-characters-between-two-special-characters) – gre_gor Dec 27 '22 at 23:55
  • The regexp is `\{[^}]*\}` – Barmar Dec 27 '22 at 23:56

2 Answers2

0

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Alternate workaround with list comprehension:

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

# John Travis was
Arifa Chan
  • 947
  • 2
  • 6
  • 23