how to slice a string by characters in 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 to make this in Python?
python
add a comment |
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 to make this in Python?
python
1
FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.
– Aran-Fey
2 hours ago
add a comment |
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 to make this in Python?
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 to make this in Python?
python
python
asked 2 hours ago
Hank ChowHank Chow
391
391
1
FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.
– Aran-Fey
2 hours ago
add a comment |
1
FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.
– Aran-Fey
2 hours ago
1
1
FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.
– Aran-Fey
2 hours ago
FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.
– Aran-Fey
2 hours ago
add a comment |
4 Answers
4
active
oldest
votes
Use itertools.groupby
:
from itertools import groupby
s = 'abccbba'
print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']
add a comment |
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']
add a comment |
Without any modules and using for loop also it can be done in 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)
New contributor
add a comment |
Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.
from functools import reduce # in python3
s='aaabccdddddaa'
reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55194935%2fhow-to-slice-a-string-by-characters-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use itertools.groupby
:
from itertools import groupby
s = 'abccbba'
print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']
add a comment |
Use itertools.groupby
:
from itertools import groupby
s = 'abccbba'
print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']
add a comment |
Use itertools.groupby
:
from itertools import groupby
s = 'abccbba'
print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']
Use itertools.groupby
:
from itertools import groupby
s = 'abccbba'
print([''.join(v) for _, v in groupby(s)])
# ['a', 'b', 'cc', 'bb', 'a']
edited 2 hours ago
Aran-Fey
20.8k53671
20.8k53671
answered 2 hours ago
AustinAustin
12.2k3929
12.2k3929
add a comment |
add a comment |
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']
add a comment |
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']
add a comment |
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']
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']
answered 2 hours ago
denis_lordenis_lor
1,36111030
1,36111030
add a comment |
add a comment |
Without any modules and using for loop also it can be done in 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)
New contributor
add a comment |
Without any modules and using for loop also it can be done in 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)
New contributor
add a comment |
Without any modules and using for loop also it can be done in 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)
New contributor
Without any modules and using for loop also it can be done in 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)
New contributor
New contributor
answered 1 hour ago
TojrahTojrah
1
1
New contributor
New contributor
add a comment |
add a comment |
Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.
from functools import reduce # in python3
s='aaabccdddddaa'
reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )
add a comment |
Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.
from functools import reduce # in python3
s='aaabccdddddaa'
reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )
add a comment |
Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.
from functools import reduce # in python3
s='aaabccdddddaa'
reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )
Just one more alternative solution. You need no import for it in python2. In python3 you need import from functools.
from functools import reduce # in python3
s='aaabccdddddaa'
reduce(lambda x,y:x[:-1]+[x[-1]+y] if len(x)>0 and x[-1][-1]==y else x+[y], s, )
answered 37 mins ago
quantummindquantummind
1,3341817
1,3341817
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55194935%2fhow-to-slice-a-string-by-characters-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
FYI, if you google "python group identical elements" or something similar you'll find plenty of recipes that would help you get started.
– Aran-Fey
2 hours ago