Gato
Gato

Reputation: 31

Python: How do I separate characters and numbers in a string

I would like to know how do I separate characters and numbers in a string and return it as an array

Eg:

"abc123" -> ["abc","123"]

"1a2bc2" -> ['1','a','2','bc','2']

"1bdc3" -> ['1','bdc','3']

Thank you for taking your time and answer me

Upvotes: 3

Views: 287

Answers (4)

Nandini  Ashok Tuptewar
Nandini Ashok Tuptewar

Reputation: 324

I have used the ascii value concept to find whether i is an integer or alphabet.

x="1a2bc2"
s=""
s1=""
lst=[]
for i in x:
    if(ord(i)>=65 and ord(i)<=122):
        if(s1!=""):
            lst.append(s1)
            s1=""
        s+=i
    else:
        if(s!=""):
            lst.append(s)
            s=""
        s1+=i
if(s1!=""):
    lst.append(s1)
if(s!=""):
    lst.append(s)    
print(lst)

Upvotes: 0

Frida Schenker
Frida Schenker

Reputation: 1509

Using Regex:

import re
input_string = "abc123de45"
output_list = re.findall(r'\d+|[a-zA-Z]+', input_string)

output_list: ['abc', '123', 'de', '45']

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36013

import itertools

def separate(string):
    return ["".join(group) for key, group in itertools.groupby(string, str.isdigit)]

print(separate("abc123"))
print(separate("1a2bc2"))
print(separate("1bdc3"))

Upvotes: 1

xjcl
xjcl

Reputation: 15309

Something like this should work:

def separate(s):
    if len(s) == 0: return s
    out = []
    tmp = [s[0]]
    for i in range(1, len(s)):
        s_im1 = s[i-1] in '0123456789'
        s_i = s[i] in '0123456789'
        if s_im1 and s_i or not s_im1 and not s_i:
            tmp.append(s[i])
        else:
            out.append(''.join(tmp))
            tmp = [s[i]]
    out.append(''.join(tmp))
    return out

Upvotes: 0

Related Questions