在60个字符后分解长字符串(添加空格)的最短方法?

end*_*eit 4 python string whitespace

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

不幸的是,如果一个字符串包含一个超过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)
Run Code Online (Sandbox Code Playgroud)