In the vast world of programming, we often come across a situation where we need to deal with strings that include both numbers and letters. This can be a mundane task at times but Python makes it simple and easy. In this tutorial, we will discuss a few methods on how to separate numbers and letters in Python.
Method 1: Using Regex
Regex, short for regular expressions, is a sequence of characters that define a search pattern. We can use Python’s built-in module re to split numbers and letters from a string.
1 2 3 4 |
import re def split_nums_letters(text): return re.findall('\d+|\D+', text) |
Here, ‘\d’ is used to match any digit (equivalent to [0-9]), and ‘\D’ is used to match any non-digit character. ‘+’ is used to match 1 or more instances. findall function will return all non-overlapping matches of pattern in string, as a list of strings.
Method 2: List Comprehension
List comprehension is a concise way of creating lists in Python. We can also use list comprehension along with the isnumeric function to segregate numbers and letters.
1 2 3 4 |
def split_nums_letters(text): return [''.join(c for c in group if c.isnumeric()) or ''.join(c for c in group if not c.isnumeric()) for group in re.findall('\d+|\D+', text)] |
In this code, we are iterating over the groups of digits and non-digits and joining the characters together. Notice how we use the ‘or’ operator to handle the case of either a string of digits or a string of non-digits.
Let’s see our functions in action:
1 2 |
text = "123abc456def" print(split_nums_letters(text)) |
It will return:
['123', 'abc', '456', 'def']
The Full code
If there are any codes inside an article, displaying the complete code at the end would be beneficial. Below, you can find the complete code for both methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import re # Using regex def split_nums_letters(text): return re.findall('\d+|\D+', text) # Using list comprehension def split_nums_letters2(text): return [''.join(c for c in group if c.isnumeric()) or ''.join(c for c in group if not c.isnumeric()) for group in re.findall('\d+|\D+', text)] text = "123abc456def" print(split_nums_letters(text)) print(split_nums_letters2(text)) |
Conclusion
To conclude, separating numbers and letters might look like a challenging task initially but Python provides several ways to make this process easy and efficient such as using Regex and List Comprehension.
These methods are fairly intuitive and easy to implement, which makes Python a very flexible and user-friendly language. We hope that this tutorial was helpful and this will make your coding journey a whole lot easier.