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?
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.
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']
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