Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a Python string with numbers and letters?

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)]
like image 858
msampaio Avatar asked Dec 19 '22 17:12

msampaio


1 Answers

You can use regular expressions for this. What we want is:

  • a string that starts with 0 or more digits,
  • a string that ends with 0 or more letters.

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)]
like image 113
El Bert Avatar answered Jan 06 '23 08:01

El Bert