开发者社区 问答 正文

以指定列宽格式化字符串

你有一些长字符串,想以指定的列宽将它们重新格式化。

展开
收起
哦哦喔 2020-04-16 19:21:57 1115 分享 版权
1 条回答
写回答
取消 提交回答
  • 使用 textwrap 模块来格式化字符串的输出。比如,假如你有下列的长字符串:
    
    s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
    the eyes, not around the eyes, don't look around the eyes, \
    look into my eyes, you're under."
    下面演示使用 textwrap 格式化字符串的多种方式:
    
    >>> import textwrap
    >>> print(textwrap.fill(s, 70))
    Look into my eyes, look into my eyes, the eyes, the eyes, the eyes,
    not around the eyes, don't look around the eyes, look into my eyes,
    you're under.
    
    >>> print(textwrap.fill(s, 40))
    Look into my eyes, look into my eyes,
    the eyes, the eyes, the eyes, not around
    the eyes, don't look around the eyes,
    look into my eyes, you're under.
    
    >>> print(textwrap.fill(s, 40, initial_indent='    '))
        Look into my eyes, look into my
    eyes, the eyes, the eyes, the eyes, not
    around the eyes, don't look around the
    eyes, look into my eyes, you're under.
    
    >>> print(textwrap.fill(s, 40, subsequent_indent='    '))
    Look into my eyes, look into my eyes,
        the eyes, the eyes, the eyes, not
        around the eyes, don't look around
        the eyes, look into my eyes, you're
        under.
    
    2020-04-16 19:22:06
    赞同 展开评论
问答地址: