美文网首页
Python3 - 以指定列宽格式化字符串

Python3 - 以指定列宽格式化字符串

作者: 惑也 | 来源:发表于2018-12-19 17:37 被阅读20次

问题

对很长的字符串,以指定的列宽将它们重新格式化。

解决方案

使用 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."

输出时每行80个字符

import textwrap
print(textwrap.fill(s, 80))

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.

输出时每行40个字符

import textwrap
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.

首行缩进4个空格

import textwrap
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.

非首行缩进4个空格

import textwrap
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.

讨论

textwrap 模块对于字符串打印是非常有用的,特别是当你希望输出自动匹配终端大小的时候。 你可以使用 os.get_terminal_size() 方法来获取终端的大小尺寸。比如:

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

相关文章

  • 【Python进阶】2.16 以指定列宽格式化字符串

    2.16 以指定列宽格式化字符串 问题 你有一些长字符串,想以指定的列宽将它们重新格式化。 解决方案 使用 tex...

  • Python3 - 以指定列宽格式化字符串

    问题 对很长的字符串,以指定的列宽将它们重新格式化。 解决方案 使用 textwrap 模块来格式化字符串的输出。...

  • Python 字符串格式化

    字符串格式化 对于如何输出格式化的字符串,是一个常见的问题。有时需要对字符串进行对齐,或者按照指定的列宽格式化字符...

  • 字符串的格式化操作

    旧式字符串格式化%运算符,位置格式化(python2) str.format字符串格式化(python3,它存在一...

  • 2019-10-26

    编码 python3源码文件默认以UTF-8编码,所有字符串都是unicode字符串。也可以为源码文件指定不同的编...

  • Yezi.CMS 标签说明文档

    date(format) 输出当前日期,或使用指定的格式化字符串格式化输出。 参数解析: format 字符串,可...

  • mysql 聚合函数和分组查询

    count():统计指定列不为NULL的记录行数;max():计算指定列的最大值,如果指定列是字符串类型,那么使用...

  • mysql 聚合函数和分组查询

    count():统计指定列不为NULL的记录行数;max():计算指定列的最大值,如果指定列是字符串类型,那么使用...

  • 2018-09-11

    常用聚合函数 COUNT():统计指定列不为NULL的记录行数;MAX():计算指定列的最大值,如果指定列是字符串...

  • 数据库 聚合函数

    聚合函数: COUNT():统计指定列不为NULL的记录行数;MAX():计算指定列的最大值,如果指定列是字符串类...

网友评论

      本文标题:Python3 - 以指定列宽格式化字符串

      本文链接:https://www.haomeiwen.com/subject/cwojkqtx.html