Hi programmers ! 


When doing CP or just solving a problem related to strings, it is highly probable that you'll need to divide that string every 2, 3 or n elements, and then moving to implement the solution, actually there are many methods for doing this in python, but I'll present here the ones that I use the most, specially when I am under time pressure ! 


1- using lists slicing : 

k = "helloworld"
n = 3
j = [k[i:i+n] for i in range(0,len(k),n)]
print(j)
first we defined the string that we want to work with, then the number we want to divide the string according to, and finally, creating a list and adding the sliced elements of the string ( k[i:i+n] ).

the output of this code is : ['hel', 'low', 'orl', 'd']


2- using the text wrap module : 

if you are in a hurry, and you don't want to use slicing, then this module is for you, actually there is a built in function that does the exact work of the above slicing, the code would be : 
n = 3
k = "helloworld"
from textwrap import wrap
v = wrap(k,n)
print(v)

 the output is the same as above : ['hel''low''orl''d']


I hope that you'll find this useful in you next problem ! 











 






Buy Website Traffic