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?
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)
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.
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']
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)
Use itertools.groupby
:
from itertools import groupby
s = 'abccbba'
print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With