2

I have been looking for a way to split a string by digits, for instance:

st = "abc4ert"
from string import digits
st = st.split(digits)
--> st = ['abc','ert']

Is there a way to do that (without including the numbers in the list)?

A.Shah
  • 43
  • 1
  • 1
  • 7

2 Answers2

2

Use Regex.

Ex:

import re

st = "abc4ert"
print(re.findall(r"[A-Za-z]+", st))

Output:

['abc', 'ert']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • 7
    It would be great if you explain this one liner `re.findall(r"[A-Za-z]+", st)`. It would be helpful to understand how it works for a larger audience reading your answer now and in the future – Sheldore Sep 21 '18 at 12:31
  • 1
    That's very basic regex literacy.`[...]` matches a single character which is one of the characters defined between the square brackets, and `A-Z` and `a-z` are character ranges whose semantics should be obvious. The `+` matches a sequence of one or more matches on the immediately preceding expression. – tripleee Sep 21 '18 at 12:33
2

Use re.split:

import re

st = "abc4ert"
st = re.split(r'\d+', st)
print(st)

Output:

['abc', 'ert']
jdehesa
  • 58,456
  • 7
  • 77
  • 121