0

Let's say 's' is a user input string and 'n' is a user input number which is less than the length of the string. Define a function strsplit(s,n) (which will accept both the user input as arguments) and split the input string in to multiple substrings each of n length seperated by a space character.

example:
lets say s="abcdefghij"
and n=3
then functions strsplit(s,n) should print 
abc def ghi j

Optimized solution with minimum iterations which I can find is as below

def strsplit(s,n):
 ln=len(s)
 for i in range(0,ln,n):
   print(s[i:i+n],end=" ")

Can be there an improved and optimized solution that the above one?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
akhil pathirippilly
  • 920
  • 1
  • 7
  • 25
  • @sshashank124 Yes its a similar question. But in this solution, function is yeilding a generator object which I need to collect in to some variable , lets say as below snew=chunks(str, n) And then I need to do " ".join(snew) to get the output in required form. So does that the optimized way with minimum cost ? – akhil pathirippilly Jan 15 '20 at 03:02
  • Best way to know is to benchmark. No point in speculating – sshashank124 Jan 15 '20 at 03:03

0 Answers0