简体   繁体   中英

Convert a string that includes both characters and integers to a list in Python

I know how to convert for instance:

'1-2=3^4/5' -> [1, '-', 2, '=', 3, '^', 4, '/', 5]

but if let's say I want to convert:

'12-34=56^78/90' -> [12, '-', 34, '=', 56, '^', 78, '/', 90]

Then I have issues.

I tried several things and it never worked perfectly - it either had an edge case where it was not working or there were issues. For instance, one of the problem I had was that the digits after the 1st one of an int was repeated as new elements.

I would greatly appreciate if anyone can take some time to help me.

Thx in advance!

EDIT: Thx to everyone for your quick answers! However, I am kinda new to programming and hence not familiar w/ the modules or methods used. Would it be possible to do it using only built-in functions?

A simple pattern that select either some digits or a non-digit, will do it

pat = re.compile(r"\d+|\D")

parts = pat.findall("1-2=3^4/5")
print(parts)  # ['1', '-', '2', '=', '3', '^', '4', '/', '5']

parts = pat.findall("12-34=56^78/90")
print(parts)  # ['12', '-', '34', '=', '56', '^', '78', '/', '90']

Use itertools.groupby to group by consecutive digits (using str.isdigit)

from itertools import groupby

s = '12-34=56^78/90'

res = ["".join(group) for k, group in groupby(s, key=str.isdigit)]
print(res)

Output

['12', '-', '34', '=', '56', '^', '78', '/', '90']

The other two answers are way, way better. But if you feel compelled to do it without any imports, here is a solution.

s = '12-34=56^78/90'

output = []
section = []
for e in s:
    try:
        e = int(e)
        section.append(e)
    except ValueError:
            output.append(''.join(map(str,section)))
            output.append(e)
            section = []
            
output.append(''.join(map(str,section)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM