+ 1

Is it possible to convert a string into a list 3-character strings at a time?

down vote favorite So for example: Vry='ABCDEFGHI' into Vry_list='ABC', 'DEF', 'GHI'. I am using Python 3 and have tried: Vry='ABCDEFGHI' lenstr=len(Vry) x=0 y=3 while y<lenstr: new=list(lstring[x:y]) x+=3 y+=3 print(new)

28th Sep 2017, 12:04 AM
Ares
Ares - avatar
1 Resposta
+ 2
Vry='ABCDEFGHI' lenstr=len(Vry) x=0 new=[] while x < lenstr: new.append(Vry[x: x+3 if x+3<=lenstr else lenstr]) x+=3 print(new) new will be equal to a list containing slices of the string each string being 3 characters long. If the last string is shorter than 3 characters it will contain all the remaining characters. new in this case will be: ['ABC', 'DEF', 'GHI']
28th Sep 2017, 3:01 AM
ChaoticDawg
ChaoticDawg - avatar