日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

《Python Cookbook 3rd》笔记(2.16):以指定列宽格式化字符串

發布時間:2023/12/13 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 《Python Cookbook 3rd》笔记(2.16):以指定列宽格式化字符串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

以指定列寬格式化字符串

問題

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

解法

使用 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, notaround the eyes, don't look aroundthe eyes, look into my eyes, you'reunder.

討論

textwrap 模塊對于字符串打印是非常有用的,特別是當你希望輸出自動匹配終端大小的時候。你可以使用 os.get terminal size() 方法來獲取終端的大小尺寸。比如:

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

fill() 方法接受一些其他可選參數來控制tab,語句結尾等。 參閱 textwrap.TextWrapper 文檔 獲取更多內容。

總結

以上是生活随笔為你收集整理的《Python Cookbook 3rd》笔记(2.16):以指定列宽格式化字符串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。