Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I slice a string every 3 indices? [duplicate]

I'm using Python to program for the lab I work at. How can I slice out every 3 characters in a given string and append it to a list?

i.e. XXXxxxXXXxxxXXXxxxXXXxxxXXX (where X or x is any given letter)

string = 'XXXxxxXXXxxxXXXxxxXXXxxxXXX'
mylist = []

for x in string:
    string[?:?:?]
    mylist.append(string)

I want the list to look like this: ['XXX','xxx','XXX','xxx','XXX'....etc]

Any ideas?

like image 240
Francis Avatar asked Apr 19 '11 04:04

Francis


People also ask

How do you find consecutive repeated characters in a string in Python?

Given a String, extract all the K-length consecutive characters. Input : test_str = 'geekforgeeeksss is bbbest forrr geeks', K = 3 Output : ['eee', 'sss', 'bbb', 'rrr'] Explanation : K length consecutive strings extracted.


1 Answers

In short, you can't.

In longer, you'll need to write your own function, possibly:

def split(str, num):
    return [ str[start:start+num] for start in range(0, len(str), num) ]

For example:

>>> split("xxxXXX", 3)
['xxx', 'XXX']
>>> split("xxxXXXxx", 3)
['xxx', 'XXX', 'xx']
like image 142
David Wolever Avatar answered Oct 26 '22 22:10

David Wolever