BitByBit
BitByBit

Reputation: 567

How to convert a string into a list without including a specific character plus without using replace and split methods?

Let's say you have:

x = "1,2,13"

and you want to achieve:

list = ["1","2","13"]

Can you do it without the split and replace methods?

What I have tried:

list=[]
for number in x:
    if number != ",":
        list.append(number)

print(list) # ['1', '2', '1', '3']

but this works only if its a single digit

Upvotes: 0

Views: 39

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96246

Here is a way using that assumes integers using itertools:

>>> import itertools
>>> x = "1,88,22"
>>> ["".join(g) for b,g in itertools.groupby(x,str.isdigit) if b]
['1', '88', '22']
>>> 

Here is a method that uses traditional looping:

>>> digit = ""
>>> digit_list = []
>>> for c in x:
...   if c.isdigit():
...     digit += c
...   elif c == ",":
...     digit_list.append(digit)
...     digit = ""
... else:
...   digit_list.append(digit)
... 
>>> digit_list
['1', '88', '22']
>>> 

In the real world, you'd probably just use regex...

Upvotes: 2

DaveBensonPhillips
DaveBensonPhillips

Reputation: 3232

You could use a regular expression:

>>> import re
>>> re.findall('(\d+)', '123,456')
['123', '456']

Upvotes: 2

Related Questions