Basically, I print a long message but I want to group all of those words into 5 character long strings. For example "iPhone 6 isn’t simply bigger — it’s better in every way. Larger, yet dramatically thinner." I want to make that "iPhon 6isn' tsimp lybig ger-i t'sbe terri never yway. Large r,yet drama tical lythi nner. "
Asked
Active
Viewed 1,480 times
-1
-
3`''.join(s.split())` and then http://stackoverflow.com/q/434287/2301450 – vaultah May 20 '15 at 15:08
2 Answers
1
As suggested by @vaultah, this is achieved by splitting the string by a space and joining them back without spaces; then using a for loop to append the result of a slice operation to an array. An elegant solution is to use a comprehension.
text = "iPhone 6 isn’t simply bigger — it’s better in every way. Larger, yet dramatically thinner." joined_text = ''.join(text.split()) splitted_to_six = [joined_text[char:char+6] for char in range(0,len(joined_text),6)] ' '.join(splitted_to_six)
I'm sure you can use the re module to get back dashes and apostrophes as they're meant to be

Ladmerc
- 1,158
- 11
- 18
1
Simply do the following.
import re
sentence="iPhone 6 isn't simply bigger - it's better in every way. Larger, yet dramatically thinner."
sentence = re.sub(' ', '', sentence)
count=0
new_sentence=''
for i in sentence:
if(count%5==0 and count!=0):
new_sentence=new_sentence+' '
new_sentence=new_sentence+i
count=count+1
print new_sentence
Output:
iPhon e6isn 'tsim plybi gger- it'sb etter ineve ryway .Larg er,ye tdram atica llyth inner .

Nishanth Duvva
- 665
- 8
- 18