Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python split string by start and end characters

Say you have a string like this: "(hello) (yes) (yo diddly)".

You want a list like this: ["hello", "yes", "yo diddly"]

How would you do this with Python?

like image 936
Name McChange Avatar asked Sep 01 '12 20:09

Name McChange


People also ask

How do you split and start and end in Python?

We can combine the index() function with slice notation to extract a substring from a string. The index() function will give us the start and end locations of the substring.

Can you split a string by multiple characters in Python?

Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.

How do you split a string after a certain number of characters Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.

How do you split a string into two places in Python?

How do you split a string in Python? Python has a built-in method you can apply to string, called . split() , which allows you to split a string by a certain delimiter.


1 Answers

import re
pattern = re.compile(r'\(([^)]*)\)')

The pattern matches the parentheses in your string (\(...\)) and these need to be escaped.
Then it defines a subgroup ((...)) - these parentheses are part of the regex-syntax.
The subgroup matches all characters except a right parenthesis ([^)]*)

s = "(hello) (yes) (yo diddly)"
pattern.findall(s)

gives

['hello', 'yes', 'yo diddly']

UPDATE:
It is probably better to use [^)]+ instead of [^)]*. The latter would also match an empty string.

Using the non-greedy modifiers, as DSM suggested, makes the pattern probably better to read: pattern = re.compile(r'\((.+?)\)')

like image 126
tzelleke Avatar answered Sep 28 '22 01:09

tzelleke