我有一些随机字符串,让我们说:
s = "This string has some verylongwordsneededtosplit"
我正在尝试编写一个函数trunc_string(string,len),它将字符串作为参数进行操作,并将'len'作为长字将被分割后的字符数。
结果应该是那样的
str = trunc_string(s, 10)
str = "This string has some verylongwo rdsneededt osplit"
现在我有这样的事情:
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)
在这部分之后,我将这个长词作为字符列表。现在我需要:
我应该以某种方式类似的方式吗? :
counter = 0
for char in split_words:
word_part.append(char)
counter = counter+1
if counter == num
在这里,我应该以某种方式将所有word_part加入到一起创建单词并进一步加入
答案 0 :(得分:6)
def split_word(word, length=10):
return (word[n:n+length] for n in range(0, len(word), length))
string = "This string has some verylongwordsneededtosplit"
print [item for word in string.split() for item in split_word(word)]
# ['This', 'string', 'has', 'some', 'verylongwo', 'rdsneededt', 'osplit']
注意:为字符串str
命名是个坏主意。它会影响内置类型。
答案 1 :(得分:5)
选项是textwrap模块
http://docs.python.org/2/library/textwrap.html
示例用法:
>>> import textwrap
>>> s = "This string has some verylongwordsneededtosplit"
>>> list = textwrap.wrap(s, width=10)
>>> for line in list: print line;
...
This
string has
some veryl
ongwordsne
ededtospli
t
>>>
答案 2 :(得分:3)
为什么不:
def truncate_long_words(s, num):
"""Splits long words in string"""
words = s.split()
for word in words:
if len(word) > num:
for i in xrange(0,len(word),num):
yield word[i:i+num]
else:
yield word
for t in truncate_long_words(s):
print t
答案 3 :(得分:3)
滥用正则表达式:
import re
def trunc_string(s, num):
re.sub("(\\w{%d}\\B)" % num, "\\1 ", s)
assert "This string has some verylongwo rdsneededt osplit" == trunc_string("This string has some verylongwordsneededtosplit", 10)
(编辑:Brian采用简化。谢谢。但我保留\B
以避免在单词长度为10个字符时添加空格。)