Victor Alexandru
Victor Alexandru

Reputation: 27

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

Upvotes: 1

Views: 1597

Answers (5)

Jayavanth
Jayavanth

Reputation: 1

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

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

Upvotes: 0

vlad-ardelean
vlad-ardelean

Reputation: 7622

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)

Upvotes: 2

midori
midori

Reputation: 4837

you could also use re module:

import re

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

Output:

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

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49310

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]

Upvotes: 1

NPE
NPE

Reputation: 500595

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 '*'.

Upvotes: 2

Related Questions