Skip to content
Related Articles
Open in App
Not now

Related Articles

Python program to separate alphabets and numbers in a string using regular expressions

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 11 Nov, 2022
Improve Article
Save Article
Like Article

 Given a string containing numbers and alphabets, the task is to write a Python program to separate alphabets and numbers from a string using regular expression.

Examples

Input: abcd11gdf15hnnn678hh4 

Output: 11 15 678 4

           abcd gdf hnnn hh

Explanation: The string is traversed from left to right and number and alphabets are separated from the given string .

Separate alphabets and numbers from a string using findall

In Python, we should import the regex library to use regular expressions. The pattern [0-9]+ is used to match the numbers in the string. Whereas ‘[a-zA-Z]’ is used to find all alphabets from the given string. We use the findall(Pattern, String) method that returns a list of all non-overlapping matches of the given pattern or regular expression in a string. 

Python3




import re
 
# Function to separate the numbers
# and alphabets from the given string
def separateNumbersAlphabets(str):
    numbers = re.findall(r'[0-9]+', str)
    alphabets = re.findall(r'[a-zA-Z]+', str)
    print(*numbers)
    print(*alphabets)
 
# Driver code
str = "adbv345hj43hvb42"
separateNumbersAlphabets(str)

Output:

 345 43 42
 adbv hj hvb

Filter alphabets and numbers from a string using split

The split(pattern, string) method splits the string together with the matched pattern, parses the string from left to right, and then produces a list of the strings that fall between the matched patterns.

Python3




import re
 
 
def separateNumbersAlphabets(str):
    numbers = []
    alphabets = []
    res = re.split('(\d+)', str)
     
    for i in res:
        if i >= '0' and i <= '9':
            numbers.append(i)
        else:
            alphabets.append(i)
             
    print(*numbers)
    print(*alphabets)
 
 
str = "geeks456for53geeks"
separateNumbersAlphabets(str)

Output:

456 53
geeks for geeks

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!