如何在60个字符后分割长字符串(添加空格)?

4 投票
3 回答
1969 浏览
提问于 2025-04-16 04:29

我正在处理一堆字符串,并把它们显示在网页上。

可惜的是,如果某个字符串里面有个单词超过60个字符,就会导致我的设计崩溃。

所以我想找一种最简单、最有效的方法,在每60个字符后面加一个空格,前提是这些字符之间没有空格,使用的是Python。

我想到的办法都很笨,比如用str.find(" ")两次,然后检查索引的差值是否大于60

如果有好的主意,我会很感激,谢谢。

3 个回答

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 )

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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)

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

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)

撰写回答