Splitting only long words in string

Posted by owca on Stack Overflow See other posts from Stack Overflow or by owca
Published on 2010-03-17T19:48:50Z Indexed on 2010/03/17 19:51 UTC
Read the original article Hit count: 374

Filed under:
|
|

I have some random string, let's say :

s = "This string has some verylongwordsneededtosplit"

I'm trying to write a function trunc_string(string, len) that takes string as argument to operate on and 'len' as the number of chars after long words will be splitted.

The result should be something like that

str = trunc_string(s, 10)
str = "This string has some verylongwo rdsneededt osplit"

For now I have something like this :

def truncate_long_words(s, num):
"""Splits long words in string"""
words = s.split()
for word in words:
    if len(word) > num:
        split_words = list(words)

After this part I have this long word as a list of chars. Now I need to :

  • join 'num' chars together in some word_part temporary list
  • join all word_parts into one word
  • join this word with the rest of words, that weren't long enough to be splitted.

Should I make it in somehow similar way ? :

counter = 0
for char in split_words:
    word_part.append(char)
    counter = counter+1
    if counter == num

And here I should somehow join all the word_part together creating word and further on

© Stack Overflow or respective owner

Related posts about python

Related posts about split