Use the str.split method:

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']
Answer from adamk on Stack Overflow
🌐
W3Schools
w3schools.com β€Ί python β€Ί ref_string_split.asp
Python String split() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The split() method splits a string into a list.
🌐
Python
docs.python.org β€Ί 3.3 β€Ί library β€Ί stdtypes.html
4. Built-in Types β€” Python 3.3.7 documentation
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.
Discussions

Split a string by a delimiter in Python - Stack Overflow
Consider the following input string: 'MATCHES__STRING' I want to split that string wherever the "delimiter" __ occurs. This should output a list of strings: ['MATCHES', 'STRING'] To spli... More on stackoverflow.com
🌐 stackoverflow.com
Split string with multiple delimiters in Python - Stack Overflow
I found some answers online, but I have no experience with regular expressions, which I believe is what is needed here. I have a string that needs to be split by either a ';' or ', ' That is, it h... More on stackoverflow.com
🌐 stackoverflow.com
Trying to understand string split()
When you're calling split() (without arguments) the split will be done on any number of spaces. It is not the same as calling split(' '). '-a-b'.split('-') # returns ['', 'a', 'b'] ' a b'.split(' ') # returns ['', 'a', 'b'] ' a b'.split() # returns ['a', 'b'] More on reddit.com
🌐 r/learnpython
7
0
January 31, 2024
split() function splitting every character?
You call c.split() but don't do anything with the result. c continues to refer to the original, unsplit, string; so c[0] gives you the first character of that string. You possibly mean c = c.split(), but it would be better to assign it to a new variable. More on reddit.com
🌐 r/learnpython
20
44
April 27, 2022
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί python β€Ί python-string-split
Python split() Method - GeeksforGeeks
July 1, 2026 - DSA Python Β· Data Science Β· NumPy Β· Pandas Β· Practice Β· Django Β· Flask Β· Last Updated : 1 Jul, 2026 Β· split() method is used to divide a string into multiple parts based on a specified separator.
🌐
Mimo
mimo.org β€Ί glossary β€Ί python β€Ί string-split-method
Learn Python's String Split Method, Simplify Text Processing
Master Python's split() method to divide strings into lists with ease. Explore examples for data parsing, text tokenization, and file processing effectively.
🌐
Hyperskill
hyperskill.org β€Ί university β€Ί python β€Ί split-in-python
Python split(): Split Strings by Delimiter with Examples
June 5, 2026 - To use the split() function, provide the delimiter as an argument within the parentheses. The delimiter can be any character or substring that you want to use as a separator. The function searches for occurrences of the delimiter within the string and breaks it down at each occurrence. # Using whitespace as a delimiter text = "Hello World! Welcome to Python!" result = text.split() print(result) # Output: ['Hello', 'World!', 'Welcome', 'to', 'Python!'] # Using a comma as a delimiter fruits = "apple,banana,orange" result = fruits.split(",") print(result) # Output: ['apple', 'banana', 'orange']
Find elsewhere
🌐
Python
docs.python.org β€Ί 3.6 β€Ί library β€Ί stdtypes.html
4. Built-in Types β€” Python 3.6.15 documentation
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.
🌐
YouTube
youtube.com β€Ί watch
Python String Splitting: String Basics & Using the .split() Method: Fundamentals - YouTube
This is a preview of the video course, "Python String Splitting". Python’s .split() method lets you divide a string into a list of substrings based on a spec...
Published: September 11, 2025
🌐
YouTube
youtube.com β€Ί python morsels
The string "split" method in Python - YouTube
Strings can be split by a substring separator. Usually the string "split" is called without any arguments, which splits on any whitespace.Article at https://...
Published: September 27, 2024
Views: 222
🌐
YouTube
youtube.com β€Ί watch
🐍 Python Tutorial #27: Splitting and Joining Strings - YouTube
In this quick Python tutorial, we cover two essential string methods: split() and join().You’ll learn:βœ… How to use split() to turn strings into listsβœ… How to...
Published: June 29, 2025
🌐
Leapcell
leapcell.io β€Ί blog β€Ί understanding-python-split-method
Understanding Python's `.split()` Method | Leapcell
July 25, 2025 - It is commonly used in text and data parsing tasks. Python's .split() method is one of the most commonly used string methods. It allows you to break up a string into a list based on a specified delimiter.
🌐
Python Reference
python-reference.readthedocs.io β€Ί en β€Ί latest β€Ί docs β€Ί str β€Ί split.html
split β€” Python Reference (The Right Way) 0.1 documentation
returns [β€˜1’, β€˜2’, β€˜3’]). Splitting an empty string with a specified separator returns [β€˜β€™].
🌐
OpenStax
openstax.org β€Ί books β€Ί introduction-python-programming β€Ί pages β€Ί 8-5-splitting-joining-strings
8.5 Splitting/joining strings - Introduction to Python Programming | OpenStax
March 13, 2024 - A string in Python can be broken into substrings given a delimiter. A delimiter is also referred to as a separator. The split() method, when applied to a string, splits the string into substrings by using the given argument as a delimiter.
Top answer
1 of 16
106

It is highly probable that re.finditer uses fairly minimal memory overhead.

def split_iter(string):
    return (x.group(0) for x in re.finditer(r"[A-Za-z']+", string))

Demo:

>>> list( split_iter("A programmer's RegEx test.") )
['A', "programmer's", 'RegEx', 'test']

I have confirmed that this takes constant memory in python 3.2.1, assuming my testing methodology was correct. I created a string of very large size (1GB or so), then iterated through the iterable with a for loop (NOT a list comprehension, which would have generated extra memory). This did not result in a noticeable growth of memory (that is, if there was a growth in memory, it was far far less than the 1GB string).

More general version:

In reply to a comment "I fail to see the connection with str.split", here is a more general version:

def splitStr(string, sep="\s+"):
    # warning: does not yet work if sep is a lookahead like `(?=b)`
    if sep=='':
        return (c for c in string)
    else:
        return (_.group(1) for _ in re.finditer(f'(?:^|{sep})((?:(?!{sep}).)*)', string))
    # alternatively, more verbosely:
    regex = f'(?:^|{sep})((?:(?!{sep}).)*)'
    for match in re.finditer(regex, string):
        fragment = match.group(1)
        yield fragment

The idea is that ((?!pat).)* 'negates' a group by ensuring it greedily matches until the pattern would start to match (lookaheads do not consume the string in the regex finite-state-machine). In pseudocode: repeatedly consume (begin-of-string xor {sep}) + as much as possible until we would be able to begin again (or hit end of string)

Demo:

>>> splitStr('.......A...b...c....', sep='...')
<generator object splitStr.<locals>.<genexpr> at 0x7fe8530fb5e8>

>>> list(splitStr('A,b,c.', sep=','))
['A', 'b', 'c.']

>>> list(splitStr(',,A,b,c.,', sep=','))
['', '', 'A', 'b', 'c.', '']

>>> list(splitStr('.......A...b...c....', '\.\.\.'))
['', '', '.A', 'b', 'c', '.']

>>> list(splitStr('   A  b  c. '))
['', 'A', 'b', 'c.', '']

(One should note that str.split has an ugly behavior: it special-cases having sep=None as first doing str.strip to remove leading and trailing whitespace. The above purposefully does not do that; see the last example where sep="\s+".)

(I ran into various bugs (including an internal re.error) when trying to implement this... Negative lookbehind will restrict you to fixed-length delimiters so we don't use that. Almost anything besides the above regex seemed to result in errors with the beginning-of-string and end-of-string edge-cases (e.g. r'(.*?)($|,)' on ',,,a,,b,c' returns ['', '', '', 'a', '', 'b', 'c', ''] with an extraneous empty string at the end; one can look at the edit history for another seemingly-correct regex that actually has subtle bugs.)

(If you want to implement this yourself for higher performance (although they are heavweight, regexes most importantly run in C), you'd write some code (with ctypes? not sure how to get generators working with it?), with the following pseudocode for fixed-length delimiters: Hash your delimiter of length L. Keep a running hash of length L as you scan the string using a running hash algorithm, O(1) update time. Whenever the hash might equal your delimiter, manually check if the past few characters were the delimiter; if so, then yield substring since last yield. Special case for beginning and end of string. This would be a generator version of the textbook algorithm to do O(N) text search. Multiprocessing versions are also possible. They might seem overkill, but the question implies that one is working with really huge strings... At that point you might consider crazy things like caching byte offsets if few of them, or working from disk with some disk-backed bytestring view object, buying more RAM, etc. etc.)

2 of 16
20

The most efficient way I can think of it to write one using the offset parameter of the str.find() method. This avoids lots of memory use, and relying on the overhead of a regexp when it's not needed.

[edit 2016-8-2: updated this to optionally support regex separators]

def isplit(source, sep=None, regex=False):
    """
    generator version of str.split()

    :param source:
        source string (unicode or bytes)

    :param sep:
        separator to split on.

    :param regex:
        if True, will treat sep as regular expression.

    :returns:
        generator yielding elements of string.
    """
    if sep is None:
        # mimic default python behavior
        source = source.strip()
        sep = "\\s+"
        if isinstance(source, bytes):
            sep = sep.encode("ascii")
        regex = True
    if regex:
        # version using re.finditer()
        if not hasattr(sep, "finditer"):
            sep = re.compile(sep)
        start = 0
        for m in sep.finditer(source):
            idx = m.start()
            assert idx >= start
            yield source[start:idx]
            start = m.end()
        yield source[start:]
    else:
        # version using str.find(), less overhead than re.finditer()
        sepsize = len(sep)
        start = 0
        while True:
            idx = source.find(sep, start)
            if idx == -1:
                yield source[start:]
                return
            yield source[start:idx]
            start = idx + sepsize

This can be used like you want...

>>> print list(isplit("abcb","b"))
['a','c','']

While there is a little bit of cost seeking within the string each time find() or slicing is performed, this should be minimal since strings are represented as continguous arrays in memory.

🌐
YouTube
youtube.com β€Ί watch
Beginner Python #3.2 - String Basics - The Split Method - YouTube
Step-by-step video shows you how to use the split() method in Python to convert strings into lists!String Basics Video: https://youtu.be/YvpHWI3S3P0Lists Vid...
Published: January 25, 2020