Separate alphabets and numbers in a string Using List Comprehension
- Take the input string from the user.
- Use list comprehension to create two lists – one for alphabets and one for numbers, by iterating over each character of the input string and checking whether it is an alphabet or a digit.
- Join the alphabets and numbers lists using a space separator to obtain the final output string.
- Print the output string.
Python3
# Take input string from the user string = "abcd11gdf15hnnn678hh4" # Use list comprehension to separate alphabets and numbers alphabets_list = [char for char in string if char.isalpha()] numbers_list = [char for char in string if char.isdigit()] # Join the lists with a space separator alphabets = ' ' .join(alphabets_list) numbers = ' ' .join(numbers_list) # Print the result print ( "Alphabets and numbers in the string are:" , alphabets, numbers) |
Output
Alphabets and numbers in the string are: a b c d g d f h n n n h h 1 1 1 5 6 7 8 4
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(n), where n is the length of the input string.
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