Python split string every n char

I want to split a string every n char and the print must be like that:

MISSISSIPPI => MI*SS*IS*SI*PP*I

I've done a program but I don't know how to change the , with a *. Here is the code:

n=input('chunk size')
s=input('Add word')
import re
r=[s[i:i+n] for i in range(0, len(s), n)]
print (r)

This is the output:

['MI', 'SS', 'IS', 'SI', 'PP', 'I']

but I want it to be like this:

MI*SS*IS*SI*PP*I

Answers


You could use str.join() for this:

>>> '*'.join(r)
'MI*SS*IS*SI*PP*I'

What this does is iterate over the strings in r, and join them, inserting '*'.


you could also use re module:

import re

r = '*'.join(re.findall('..|.$', s))

Output:

'MI*SS*IS*SI*PP*I'

Well at the point that you're at, you just have 1 more line to add:

r = '*'.join(r)

So then your program becomes

n=input('chunk size')
s=input('Add word')
import re
r=[s[i:i+n] for i in range(0,len(s),n)]
r = '*'.join(r)
print (r)

Unpack it and then use a custom separator:

>>> print(*r, sep='*')
MI*SS*IS*SI*PI

If you want the brackets in the output, use string formatting instead.

>>> print('[{}]'.format('*'.join(r)))
[MI*SS*IS*SI*PI]

We can use split and join methods of string data structure.

x = 'MI*SS*IS*SI*PP*I' xlist = x.split('*') '*'.join(xlist)


Need Your Help

Transmitting hand-written information over a network

algorithm networking computer-science

A teacher is writing on a blackboard and we want to pass all the information on the blackboard over a low-bandwidth network in real-time. How do we do it?

Force form to change with jQuery

javascript jquery forms

Can anyone tell me how to force a form change in jQuery. I am manually setting values with jQuery, but the form doesn't enter this function: