How to Split Numeric and Letters From a String in Python

How to split the string into substrings of either letters or numbers by utilizing the boundary between a letter and a number and vice versa.

: Have a look at the following examples of what you want to accomplish.

'111A222B333C'     --->    ['111', 'A', '222', 'B', '333', 'C']
'MEDIUM24' ---> ['MEDIUM', '24']
'Amazing Python' ---> ['Amazing', ' Python']

So, we have few pattern matching methods in Python which I will be using in the solution.

1. Using re.split()

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.

Read DOCS.

CODE:

import reaString = '111A222B333C'res = re.split('(\d+)', aString)print(res)

Output:

2. re.findall()

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

Read DOCS.

Code:

import reaString = 'MEDIUM24'res = re.findall('(\d+|[A-Za-z]+)', aString)print(res)

Output:

3. Using itertools.groupby()

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

Read DOCS.

Code:

from itertools import groupbyaString = '111A222B333C'res = [''.join(g) for _, g in groupby(aString, str.isalpha)]print(res)

Output:

To become felicitous in coding, you require to get out over there and solve genuine issues for genuine people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really require in practice. After all, what’s the use of acquiring theory that no one ever needs?

--

--

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shahzaib Chadhar

I am Shahzaib Chadhar, a hard-working, reliable freelance Full Stack Developer and Data Extraction Specialist.