Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I slice a string by characters in Python? [duplicate]

Tags:

python

There is a string with one or more characters. I want to slice the list so that the adjoining same characters are in the same element. For example:

'a' -> ['a']
'abbbcc' -> ['a', 'bbb', 'cc']
'abcabc' -> ['a', 'b', 'c', 'a', 'b', 'c']

How do I make this in Python?

like image 425
Hank Chow Avatar asked Mar 16 '19 08:03

Hank Chow


People also ask

How do you slice a character in a string in Python?

Method 1: Using slice() method The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step). Syntax: slice(stop) slice(start, stop, step)

How do I slice a string by character?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


3 Answers

It can be achieved with re.finditer():

import re
s = 'aabccdd'
print([m.group(0) for m in re.finditer(r"(\w)\1*", s)])
#['aa', 'b', 'cc', 'dd']
like image 57
denis_lor Avatar answered Oct 22 '22 17:10

denis_lor


Without any modules and using a for loop it can also be done in an interesting way:

l = []
str = "aabccc"
s = str[0]
for c in str[1:]:

    if (c != s[-1]):
        l.append(s)
        s = c
    else:
        s = s + c
l.append(s)
print(l)
like image 3
Tojra Avatar answered Oct 22 '22 16:10

Tojra


Use itertools.groupby:

from itertools import groupby

s = 'abccbba'

print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']
like image 20
Austin Avatar answered Oct 22 '22 18:10

Austin