I have a string in python without white space and I want python to split this string for every 3 letters so like 'antlapcap'
,
For example would be ['ant', 'lap', 'cap']
is there any way to do this?
Asked
Active
Viewed 3,786 times
0

James K
- 3,692
- 1
- 28
- 36

Yousef Radwan
- 33
- 1
- 7
3 Answers
0
not sure if theres a more efficient way of doing it but ,try:
string = "antlapcap"
list = []
i = 0
for i in range(i,len(string)):
word =string[i:i+3]
list.append(word)
i=i+3
j = list
b =j[::3]
print(b)

jack
- 23
- 2
- 10
0
Iterate over the string, adding to a string variable until it reaches a certain length, then append the string to a list. eg.
def split_at_nth(string, split_size):
s = ''
res = []
for char in string:
s += char
if len(s) == split_size:
res.append(s)
s = ''
return res
s = 'antlapcap'
print(split_at_nth(s, 3)) # prints ['ant', 'lap', 'cap']
Another option would be to use a series of list comprehensions:
def split_at_nth(string, split_size):
res = [c for c in string]
res = [sub for sub in zip(*[iter(res)]*3)]
res = [''.join(tup) for tup in res]
return res
s = 'antlapcap'
print(split_at_nth(s, 3)) # prints ['ant', 'lap', 'cap']

Christian Dean
- 22,138
- 7
- 54
- 87
0
This is a simple way to do it.
>>> a="abcdefghi"
>>> x=[]
>>> while len(a) != 0:
... x.append(a[:3])
... a=a[3:]
...
>>> a
''
>>> x
['abc', 'def', 'ghi']
This simply appends to the list x
the first 3 characters of the string a
, then redefines a
to be everything in a
except the first 3 characters and so on until a
is exhausted.
With a hat tip to user @vlk (Split python string every nth character?), although I have altered the while
statement

Community
- 1
- 1

Rolf of Saxony
- 21,661
- 5
- 39
- 60