Home > Software engineering >  Python Split String at First Non-Alpha Character
Python Split String at First Non-Alpha Character

Time:09-21

Say I have the strings such as 'ABC)D.' or 'AB:CD/'. How can I split them at the first non-alphabetic character to end up with ['ABC', 'D.'] and ['AB', 'CD/']? Is there a way to do this without regex?

CodePudding user response:

You can use a loop

a = 'AB$FDWRE'
i = 0
while i<len(a) and a[i].isalpha():
    i  = 1

>>> a[:i]
'AB'
>>> a[i:]
'$FDWRE'

CodePudding user response:

One option would be to find the location of the first non-alphabetic character:

def split_at_non_alpha(s):
    try:
        split_at = next(i for i, x in enumerate(s) if not x.isalpha())
        return s[:split_at], s[split_at 1:]
    except StopIteration: # if not found
        return (s,)

print(split_at_non_alpha('ABC)D.')) # ('ABC', 'D.')
print(split_at_non_alpha('AB:CD/')) # ('AB', 'CD/')
print(split_at_non_alpha('.ABCD')) # ('', 'ABCD')
print(split_at_non_alpha('ABCD.')) # ('ABCD', '')
print(split_at_non_alpha('ABCD')) # ('ABCD',)
  • Related