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?
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.
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.
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 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.
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'\((.+?)\)')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With