Use the str.split method:
>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
Answer from adamk on Stack OverflowTrying to understand string split()
Split a string by a delimiter in Python - Stack Overflow
python - Split Strings into words with multiple word boundary delimiters - Stack Overflow
Split string with multiple delimiters in Python - Stack Overflow
Hi,
I am unable to wrap my head around how string split() works in Python. Consider the following examples:
‘/‘.split(‘/‘) # Outputs [‘’, ‘’]
‘ a b ‘.split() # Outputs [‘a’, ‘b’]
I was expecting the second example to return [‘’, ‘a’, ‘b’, ‘’]. Why does split() omit the empty strings in the output list?
Use the str.split method:
>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
Besides split and rsplit, there is partition/rpartition. It separates string once, but the way question was asked, it may apply as well.
Example:
>>> "MATCHES__STRING".partition("__")
('MATCHES', '__', 'STRING')
>>> "MATCHES__STRING".partition("__")[::2]
('MATCHES', 'STRING')
And a bit faster then split("_",1):
$ python -m timeit "'validate_field_name'.split('_', 1)[-1]"
2000000 loops, best of 5: 136 nsec per loop
$ python -m timeit "'validate_field_name'.partition('_')[-1]"
2000000 loops, best of 5: 108 nsec per loop
Timeit lines are based on this answer
re.split()
re.split(pattern, string[, maxsplit=0])
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.)
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
A case where regular expressions are justified:
import re
DATA = "Hey, you - what are you doing here!?"
print re.findall(r"[\w']+", DATA)
# Prints ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
Luckily, Python has this built-in :)
import re
# Regex pattern splits on substrings "; " and ", "
re.split('; |, ', string_to_split)
Update:
Following your comment:
>>> string_to_split = 'Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n', string_to_split)
['Beautiful', 'is', 'better', 'than', 'ugly']
Do a str.replace('; ', ', ') and then a str.split(', ')