zoukankan      html  css  js  c++  java
  • 【python cookbook】【字符串与文本】16.以固定的列数重新格式化文本

    问题:重新格式化一些很长的字符串,以指定的列数来显示

    解决方案:textwrap模块的fill()方法来实现

    # A long string
    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."
    
    import textwrap
    
    print(textwrap.fill(s, 70))
    print()
    
    print(textwrap.fill(s, 40))
    print()
    
    print(textwrap.fill(s, 40, initial_indent='    ')) #initial_indent:在第一行的行首添加指定的字符显示。默认是空白。如果首行是空白行就不会添加。print()
    
    print(textwrap.fill(s, 40, subsequent_indent='    ')) #subsequent_indent:除了第一行,所有其它行都在行首添加这个字符串的输出。默认为空。
    print()
    >>> ================================ RESTART ================================
    >>> 
    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.
    
    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.
    
        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.
    
    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.
    
    >>> 

    关于终端的尺寸大小,可以通过os.get_terminal_size()来获取:

    >>> import os
    >>> os.get_terminal_size().columns
    80

    fill()方法还有其他的额外的选项可以用来控制制表符、句号等,请参阅textwrap.TextWrapper类的文档  https://docs.python.org/3.3/library/textwrap.html#textwrap.TextWrapper

  • 相关阅读:
    C++中合并两个排行榜的思路
    C++函数类型以及函数表实验
    C++获取两个值的差距比
    windows下的bash工具:winbash
    导入sql文件提示2006错误的解决办法
    C++延迟delete对象方案:采用unique_ptr托管欲删除的对象指针
    C++使用lower_bound快速查询分段配置
    sqlserver数据库操作
    判断 iframe 是否加载完成的完美方法
    SQL数据缓存依赖 [SqlServer | Cache | SqlCacheDependency ]
  • 原文地址:https://www.cnblogs.com/apple2016/p/5793772.html
Copyright © 2011-2022 走看看