0

I am trying to split a string at a certain point using python

What I want to do is as follows:

let's say we have a string as

str = "123456789123456789"

I want to break this string in to parts where each part has a length of 5 or less (the last part)

so the output of the above string should look like this:


    l: 12345
    r: 67891
    l: 23456
    r: 789

This is my code I am trying to do this:


            errormsg = "123456789123456789"
            if len(errormsg) > 5 :
                print("yes")
                splitat = 5
                str = errormsg
                l, r = str[:splitat], str[splitat:]
                print("l: " + l)
                print("r: " + r)

                while len(r) > 5:
                    # print("hi")                
                    str = r
                    splitat = 5
                    l, r = str[:splitat], str[splitat:]
                    print("l: " + l)
                    print("r: " + r)


But it gives a weird output like this:


yes
l: 12345
r: 6789123456789
l: 67891
r: 23456789
l: 23456
r: 789

Can someone tell me how to fix this?

Jananath Banuka
  • 493
  • 3
  • 11
  • 22
  • you dont say what you want the output to be? so its hard to say how to fix it. The output you gett is because you keep printing the l and r values after you split them but you never store these – Chris Doyle Dec 31 '19 at 14:56
  • 1
    Does this answer your question? [Split string every nth character?](https://stackoverflow.com/questions/9475241/split-string-every-nth-character) – Frederik Baetens Dec 31 '19 at 14:59
  • The reason is that you give the slice for `r` no end position, so it encompasses the rest of the string – C.Nivs Dec 31 '19 at 15:02
  • errormsg = "123456789123456789" if len(errormsg) > 5 : print("yes") splitat = 5 str = errormsg l, r = str[:splitat], str[splitat:splitat*2] print("l: " + l) print("r: " + r) while len(str) > 5: # print("hi") splitat = 5 l, r = str[:splitat], str[splitat:splitat*2] str = str[splitat*2:splitat*3] print("l: " + l) print("r: " + r) –  Dec 31 '19 at 15:10

2 Answers2

2

I'd just use the recipe from the itertools module:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
gct
  • 14,100
  • 15
  • 68
  • 107
2

Try:

str = "123456789123456789"
splitted_string = []

for i in range(0, len(str), 5):
    splitted_string.append(str[i:i+5])

print(splitted_string)
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17