I have strings that have optional numbers and letters, such as '01a', 'b' and '02'. These strings have always two parts, numbers on the left, and letters on the right side. I'd like to split these strings to get the numbers and letters separately. How can I define mySplit
in a way to get this result?
>>> map(mySplit, ['01123absd', 'bsdf', '02454'])
[('01123', 'absd'), (None, 'bsdf'), ('02454', None)]
You can use regular expressions for this. What we want is:
Note that the regex
will create named groups, it is also compiled once to be more efficient every time is it called.
import re
regex = re.compile("^(?P<numbers>\d*)(?P<letters>\w*)$")
def myFunction(entry):
(numbers, letters) = regex.search(entry).groups()
return (numbers or None, letters or None)
map(myFunction, ['01123absd', 'bsdf', '02454'])
The call on the last line gives the following output:
[('01123', 'absd'), (None, 'bsdf'), ('02454', None)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With