2010-09-23 35 views
4

我正在处理一串字符串并在网页上显示它们。在60个字符后分解长字符串(添加空格)的最短途径?

不幸的是,如果一个字符串包含一个长于60个字符的单词,它会让我的设计崩溃。

因此,我正在寻找最简单,最有效的方法来在每个60个字符后面添加一个空格,而不需要在Python中的字符串中使用空格。

我只想出了笨重的解决方案,如使用str.find(" ")两次,并检查索引差异是否为> 60

任何想法赞赏,谢谢。

回答

5
 
>>> import textwrap 
>>> help(textwrap.wrap) 
wrap(text, width=70, **kwargs) 
    Wrap a single paragraph of text, returning a list of wrapped lines. 

    Reformat the single paragraph in 'text' so it fits in lines of no 
    more than 'width' columns, and return a list of wrapped lines. By 
    default, tabs in 'text' are expanded with string.expandtabs(), and 
    all other whitespace characters (including newline) are converted to 
    space. See TextWrapper class for available keyword args to customize 
    wrapping behaviour. 
>>> s = "a" * 20 
>>> s = "\n".join(textwrap.wrap(s, width=10)) 
>>> print s 
aaaaaaaaaa 
aaaaaaaaaa 

当网页被浏览器处理时,插入的额外换行符将被视为空格。

或者:

def break_long_words(s, width, fix): 
    return " ".join(x if len(x) < width else fix(x) for x in s.split()) 

def handle_long_word(s): # choose a name that describes what action you want 
    # do something 
    return s 

s = "a" * 20 
s = break_long_words(s, 60, handle_long_word) 
+0

+1 [/线程] textwrap是一个不错的发现。 – aaronasterling 2010-09-23 08:52:53

+0

textwrap是完美的,谢谢。 – endzeit 2010-09-23 09:45:21

0

def make_wrappable(your_string): 
    new_parts = [] 
    for x in your_string.split(): 
     if len(x)>60: 
      # do whatever you like to shorten it, 
      # then append it to new_parts 
     else: 
      new_parts.append(x)   
    return ' '.join(new_parts) 
0
def splitLongWord (word): 
    segments = list() 
    while len(word) > 0: 
     segments.append(a[:60]) 
     word = a[60:] 
    return ' '.join(segments) 

myString = '...' # a long string with words that are longer than 60 characters 
words = list() 
for word in myString.split(' '): 
    if len(word) <= 60: 
     words.append(word) 
    else: 
     words.extend(splitLongWord(word)) 
myString = ' '.join(words) 
相关问题