Separate Alphabets and Numbers in a String - Python
The task is to separate alphabets and numbers from a string. For example, given "a1b2c3", the output should be alphabets "abc" and numbers "123".
Using List Comprehension
List comprehension offers a concise and efficient way to separate alphabets and numbers from a string. It iterates through each character and filters them based on whether they are alphabets or digits, combining the results into separate strings
s = "a1b2c3d4"
alpha = ''.join([char for char in s if char.isalpha()])
nums = ''.join([char for char in s if char.isdigit()])
print("Alphabets:", alpha)
print("Numbers:", nums)
Output
Alphabets: abcd Numbers: 1234
Explanation:
- List Comprehension for Filtering: The program uses list comprehensions to filter characters from input_string. The first comprehension selects characters that are alphabets using char.isalpha(), while the second selects digits using char.isdigit().
- Joining Filtered Characters: The join() method combines the filtered characters from each list comprehension into strings, storing alphabets in alphabets and digits in numbers, which are then printed.
Using a For Loop
Using a for loop is a straightforward way to iterate through a string and separate its characters based on their type. This approach allows us to easily identify and categorize alphabets and numbers into separate variables.
s = "a1b2c3d4"
alpha = ""
nums = ""
for char in s:
if char.isalpha():
alpha += char
elif char.isdigit():
nums += char
print("Alphabets:", alpha)
print("Numbers:", nums)
Output
Alphabets: abcd Numbers: 1234
Explanation:
- The program uses a for loop to iterate through each character in the string input_string. It checks if the character is an alphabet using char.isalpha() or a digit using char.isdigit(), classifying them accordingly.
- Based on the classification, alphabets are appended to the alphabets string, and digits are appended to the numbers string. Finally, both strings are printed to display the separated characters.
Using Filter
filter() function provides a clean way to separate alphabets and numbers from a string by applying str.isalpha and str.isdigit as filters. The join() method combines the filtered characters into separate strings for alphabets and numbers.
s = "a1b2c3d4"
alpha = ''.join(filter(str.isalpha, s))
nums = ''.join(filter(str.isdigit, s))
print("Alphabets:", alpha)
print("Numbers:", nums)
Output
Alphabets: abcd Numbers: 1234
Explanation:
- Using filter() for Character Selection: The filter() function applies str.isalpha to extract only alphabetic characters and str.isdigit to extract numeric characters from input_string.
- Combining Results with join(): The join() method merges the filtered characters into two separate strings, alphabets and numbers, which are then printed.