将长字符串换成换行符的好方法吗?

发布于 2021-01-29 18:39:39

在我的项目中,我有一堆从文件中读取的字符串。当在命令控制台中打印时,其中大多数字符的长度超过80个字符并环绕,看起来很丑。

我希望能够让Python读取该字符串,然后测试其长度是否超过75个字符。如果是这样,则将字符串分成多个字符串,然后在新行上一个接一个地打印。我也希望它很聪明,而不是断断续续。即"The quick brown <newline> fox..."代替"the quick bro<newline>wn fox..."

我试过修改类似的代码,该代码会在设置长度后将字符串截断,但只是将字符串丢弃而不是将其放在新行中。

我可以使用哪些方法来完成此任务?

关注者
0
被浏览
39
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以使用textwrap模块:

    >>> import textwrap
    >>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
    >>> print(textwrap.fill(strs, 20))
    In my project, I
    have a bunch of
    strings that are
    read in from a file.
    Most of them, when
    printed in the
    command console,
    exceed 80 characters
    in length and wrap
    around, looking
    ugly.
    

    帮助
    textwrap.fill

    >>> textwrap.fill?
    
    Definition: textwrap.fill(text, width=70, **kwargs)
    Docstring:
    Fill a single paragraph of text, returning a new string.
    
    Reformat the single paragraph in 'text' to fit in lines of no more
    than 'width' columns, and return a new string containing the entire
    wrapped paragraph.  As with wrap(), tabs are expanded and other
    whitespace characters converted to space.  See TextWrapper class for
    available keyword args to customize wrapping behaviour.
    

    使用regex,如果你不想合并一行到另一行:

    import re
    
    
    strs = """In my project, I have a bunch of strings that are.
    Read in from a file.
    Most of them, when printed in the command console, exceed 80.
    Characters in length and wrap around, looking ugly."""
    
    print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))
    
    # Reading a single line at once:
    for x in strs.splitlines():
        print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))
    

    输出:

    In my project, I have a bunch of strings
    that are.
    Read in from a file.
    Most of them, when printed in the
    command console, exceed 80.
    Characters in length and wrap around,
    looking ugly.
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看