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

标签 python string whitespace

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

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

因此,我正在寻找最简单、最有效的方法来在 python 中的字符串中每 60 个字符后添加一个没有空格的空格。

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

任何想法表示赞赏,谢谢。

最佳答案

>>> 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

Any extra newlines inserted will be treated as space when the web page is processed by the browser.

Alternatively:

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)

关于python - 在 60 个字符后分解长字符串(添加空格)的最短方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3776627/

相关文章:

python - 让 Python 包以不同的名称安装自身

python - AWS CDK,为 Route53 中的现有托管区域创建别名记录

c++ - 获取字符串的最后一行

java - 字符串中的数字频率

java - 如果出现不同的字符,如何拆分字符串?

java - 如何从字符串的开头删除空格?

bash - 使用 bash 脚本将下划线替换为空格

python - 如何计算 python pandas 中的特定单元格值?

whitespace - 内联 block 后的奇怪空间。不介于

python - 清除 Django 中验证错误时的所有表单字段