Separate alphabets and numbers using isalpha() and isnumeric()
Step-by-step approach:
- Create two empty strings for storing the alphabets and numbers.
- Iterate through each character in the given string using a for loop.
- Check if the character is an alphabet or a number using the isalpha() and isnumeric() functions respectively.
- If the character is an alphabet, append it to the alphabets string. If it is a number, append it to the numbers string.
- Print the final alphabets and numbers strings.
Below is the implementation of the above approach:
Python3
def separateNumbersAlphabets( str ): # Create empty strings for storing the alphabets and numbers numbers = '' alphabets = '' # Iterate through each character in the given string for char in str : # Check if the character is an alphabet if char.isalpha(): # If it is an alphabet, append it to the alphabets string alphabets + = char # Check if the character is a number elif char.isnumeric(): # If it is a number, append it to the numbers string numbers + = char # Print the final alphabets and numbers strings print (numbers) print (alphabets) # Driver code str = "adbv345hj43hvb42" separateNumbersAlphabets( str ) |
Output
3454342 adbvhjhvb
Time complexity: O(n), where n is the length of the given string.
Auxiliary space: O(n), for storing the alphabets and numbers strings.
Python program to separate alphabets and numbers in a string
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 4abcd gdf hnnn hh
Explanation: The string is traversed from left to right and number and alphabets are separated from the given string .
Contact Us