Python每日一練0017

2021-08-18 16:52:56 字數 1613 閱讀 4673

你有一些長字串,想以指定的列寬將它們重新格式化。

使用textwrap模組的fillwrap函式

假設有乙個很長的字串

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

如果直接輸出的話,可讀性會比較差

>>> print(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.

我們可以使用fill函式來將這個長字串自動切分為若干短字串,只需要指定width即可

>>> print(textwrap.fill(s, width=60))

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.

也可以使用wrap函式,但是效果是一樣的,只不過wrap函式返回的是乙個列表而不是字串

>>> print(textwrap.fill(s, width=60, 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.

如果希望能匹配終端的大小的話,我們可以使用os.get_terminal_size()來得到終端的寬度,然後傳給width

>>> textwrap.fill(s, width=os.get_terminal_size().columns)
>>> print(wrap.fill(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.

python cookbook

python每日一練

人生苦短,我用python 2018.6.5 有個目錄,裡面是你自己寫過的程式,統計一下你寫過多少行 包括空行和注釋,但是要分別列出來 coding utf 8 import re import glob defcodecolletion path filelist glob.glob path p...

Python每日一練

人生苦短,我用python 2018.6.13 最近事情有點多,有幾天沒寫了,正好最近需要統計一下各組排名,也就拿python代替手工了 各組給出其他組的排名,統計每個組最終的得分,第一名為0.5,第二名0.4,以此類推。coding utf 8 groups 3,2,5,4,6 1,3,5,6,4...

Python每日一練0002

如何序列化輸出元素包含字串元組的字串元組 好繞 舉個例子 zoo1 monkey elephant zoo2 python zoo1 將zoo2輸出為python,monkey,elephant容易想到使用join 函式,但join 函式要求元素必須都是字串型別,否則會丟擲typeerror錯誤 z...