文章目录

  • 字符串格式化
    • ljust()、rjust()、center()
    • format()
      • 字符串对齐
      • 替换内嵌变量字符串
    • join()
    • textwrap
    • 参考资料
      • 来源

字符串格式化


对于如何输出格式化的字符串,是一个常见的问题。有时需要对字符串进行对齐,或者按照指定的列宽格式化字符串,亦或是对字符串进行拼接,有时候还需要构造内嵌变量的字符串等。Python 提供了一些方法对上述情况进行实现。

ljust()、rjust()、center()


对于基本字符串对齐操作,可以使用字符串内置方法 ljust()rjust()center()。如下示例:

>>> text = "Hello World"
>>> text.ljust(20)
'Hello World         '
>>> text.rjust(20)
'         Hello World'
>>> text.center(20)
'    Hello World     '
>>>

上述三个方法有两个参数 widthfillcharwidth 用于返回长度为 width 的字符串,使用指定的 fillchar 填充空位(默认使用 ASCII 空格符,可指定其他字符)。

其中 ljust() 原字符串在其中靠左对齐,rjust() 靠右对齐,center() 在正中。

尝试使用指定非空格的 fillchar 作为填充字符,例如:

>>> text.ljust(20, '-')
'Hello World---------'
>>> text.rjust(20, '=')
'=========Hello World'
>>> text.center(20, '*')
'****Hello World*****'

这三个方法还有个特性,如果参数 width 小于等于 len(s) 字符串的长度,则返回原字符串的副本。

>>> len(text)
11
>>> text.ljust(11)
'Hello World'
>>> text.rjust(10)
'Hello World'
>>> text.center(9)
'Hello World'

format()


字符串对齐

除了使用上述三种方法对字符串进行对齐,format() 也能够实现对齐字符串。

各种对齐选项含义如下:

选项 含义
‘<’ 强制字段在可用空间内向左对齐(大多数对象的默认值)
‘>’ 强制字段在可用空间内向右对齐(数字的默认值)
‘^’ 强制字段在可用空间内居中

使用 format() 对字符串进行对齐,在上述对齐选项后面添加指定宽度,示例如下:

>>> format(text, '>20')
'         Hello World'
>>> format(text, '<20')
'Hello World         '
>>> format(text, '^20')
'    Hello World     '

如果需要指定非空格填充字符,可在对齐选项前面添加 fill 字符,可以是任意字符。

>>> format(text, '->20')
'---------Hello World'
>>> format(text, '=<20')
'Hello World========='
>>> format(text, '*^20')
'****Hello World*****'

format() 可用于格式化多个值,比如:

>>> '{:>10s} {:>10s}'.format('Hello', 'World')
'     Hello      World'

s 为字符串表示类型,表示字符串格式,字符串的默认类型,可省略。

format() 不单只适用于字符串。它可以格式化任何值。例如,格式化数字:

>>> format(x, '>10')
'    1.2345'
>>> format(x, '^10.2f')
'   1.23   '

f 为浮点型表示类型,表示定点表示。其中 .2f 表示以 f 格式化的浮点数值在小数点后显示 2 个数位。

相比 ljust()rjust()center()format() 更通用,同时还可以格式化任意对象,不仅仅是字符串。

替换内嵌变量字符串

字符串的 format() 方法,能够用指定的值替换内嵌变量字符串中的变量。

>>> s = '{name} was born in {country}'
>>> s.format(name='Guido',country='Netherlands')
'Guido was born in Netherlands'

如果被替换的变量能够在变量域中找到,可以结合使用 format_map()vars()。示例如下:

>>> name = 'Guido'
>>> country = 'Netherlands'
>>> s.format_map(vars())
'Guido was born in Netherlands'
>>>

format()format_map() 有一个缺陷,不能很好处理变量缺失的情况,如下示例:

>>> s.format(name='Gudio')
Traceback (most recent call last):File "<stdin>", line 1, in <module>
KeyError: 'country'

这里可以使用 __missing__() 方法,定义一个含此方法的字典来避免上面发生的错误。例如:

>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> s.format_map(Default(name='Gudio'))
'Guido was born in country'

若需完全了解 format() 函数的相关特性,请参考 Python文档。

join()


若需合并的字符串是在一个序列或者 iterable 中,建议使用 join() 方法。示例如下:

>>> words = ['Hello', 'World']
>>> ' '.join(words)
'Hello World'
>>> ','.join(words)
'Hello,World'

join(iterable) 方法返回的是一个由 iterable 中的字符串拼接的字符串。如果 iterable 中存在任何非字符值包括 bytes 对象则会引发 TypeError。调用该方法的字符串将作为元素之间的分隔。例如上述例子的空格 ' '和 逗号 ','

还有一种拼接字符串的方法是用加号 +,但是这种效率通常是非常低的。这种加号连接会引起内存复制以及垃圾回收机制。不建议使用下列方法连接字符串:

s = ''
for word in words:s += word

textwrap


长字符串输出的时候,有时需要进行一定的格式化输出,如下示例:

>>> s = "The Zen of Python, by Tim Peters \
... Beautiful is better than ugly.\
... Explicit is better than implicit. \
... Simple is better than complex. \
... Complex is better than complicated. \
... Flat is better than nested. \
... Sparse is better than dense. \
... Readability counts. \
... Special cases aren't special enough to break the rules. \
... Although practicality beats purity. \
... Errors should never pass silently. \
... Unless explicitly silenced. \
... In the face of ambiguity, refuse the temptation to guess. \
... There should be one-- and preferably only one --obvious way to do it. \
... Although that way may not be obvious at first unless you're Dutch. \
... Now is better than never. \
... Although never is often better than *right* now. \
... If the implementation is hard to explain, it's a bad idea. \
... If the implementation is easy to explain, it may be a good idea. \
... Namespaces are one honking great idea -- let's do more of those!">>> import textwrap
>>> print(textwrap.fill(s, 70))
The Zen of Python, by Tim Peters Beautiful is better than
ugly.Explicit is better than implicit. Simple is better than complex.
Complex is better than complicated. Flat is better than nested. Sparse
is better than dense. Readability counts. Special cases aren't special
enough to break the rules. Although practicality beats purity. Errors
should never pass silently. Unless explicitly silenced. In the face of
ambiguity, refuse the temptation to guess. There should be one-- and
preferably only one --obvious way to do it. Although that way may not
be obvious at first unless you're Dutch. Now is better than never.
Although never is often better than *right* now. If the implementation
is hard to explain, it's a bad idea. If the implementation is easy to
explain, it may be a good idea. Namespaces are one honking great idea
-- let's do more of those!>>> print(textwrap.fill(s, 40))
The Zen of Python, by Tim Peters
Beautiful is better than ugly.Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the temptation to
guess. There should be one-- and
preferably only one --obvious way to do
it. Although that way may not be obvious
at first unless you're Dutch. Now is
better than never. Although never is
often better than *right* now. If the
implementation is hard to explain, it's
a bad idea. If the implementation is
easy to explain, it may be a good idea.
Namespaces are one honking great idea --
let's do more of those!>>> print(textwrap.fill(s, 40, initial_indent='    '))The Zen of Python, by Tim Peters
Beautiful is better than ugly.Explicit
is better than implicit. Simple is
better than complex. Complex is better
than complicated. Flat is better than
nested. Sparse is better than dense.
Readability counts. Special cases aren't
special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. In the face
of ambiguity, refuse the temptation to
guess. There should be one-- and
preferably only one --obvious way to do
it. Although that way may not be obvious
at first unless you're Dutch. Now is
better than never. Although never is
often better than *right* now. If the
implementation is hard to explain, it's
a bad idea. If the implementation is
easy to explain, it may be a good idea.
Namespaces are one honking great idea --
let's do more of those!>>> print(textwrap.fill(s, 40, subsequent_indent='    '))
The Zen of Python, by Tim PetersBeautiful is better thanugly.Explicit is better thanimplicit. Simple is better thancomplex. Complex is better thancomplicated. Flat is better thannested. Sparse is better than dense.Readability counts. Special casesaren't special enough to break therules. Although practicality beatspurity. Errors should never passsilently. Unless explicitlysilenced. In the face of ambiguity,refuse the temptation to guess.There should be one-- and preferablyonly one --obvious way to do it.Although that way may not be obviousat first unless you're Dutch. Now isbetter than never. Although never isoften better than *right* now. Ifthe implementation is hard toexplain, it's a bad idea. If theimplementation is easy to explain,it may be a good idea. Namespacesare one honking great idea -- let'sdo more of those!
>>>

textwrap 模块中的 fill 方法用于对 text 中的单独段落自动换行,返回包含被换行段落的单独字符串。fill 函数属于快捷函数,若更复杂的情况,建议使用 TextWrapper 提高效率。可参阅 textwrap.TextWrapper 文档 获取更多的内容。

参考资料


来源

  1. David M. Beazley;Brian K. Jones.Python Cookbook, 3rd Edtioni.O’Reilly Media.2013.
  2. “6.1. string — Common string operations”.docs.python.org.Retrieved 7 January 2020
  3. '2. Built-in Functions".docs.python.org.Retrieved 6 January 2020
  4. “4. Built-in Types”.docs.python.org.Retrieved 3 January 2020
  5. “6.4. textwrap — Text wrapping and filling”.docs.python.org.Retrieved 9 January 2020

以上就是本篇的主要内容


欢迎关注『书所集录』公众号

Python 字符串格式化相关推荐

  1. python 字符串格式化是打印不同类型更简单一些

    Python 支持格式化字符串的输出 与 C 中 sprintf 函数一样的语法 下面写3中不同类型的数据合在一起打印 name = "张三丰" height = 1.88 wei ...

  2. python 字符串格式化%s_Python字符串格式化%s%d%f详解

    关于讨论输出格式化的问题,小编不是一时兴起,之前学习python的时候就经常遇到输出时"%d",一直没有仔细学习,今天又看到了,下面分享一个简单实例,python输出99乘法表: ...

  3. python的格式化输出学号_安利三个关于Python字符串格式化进阶知识

    点击蓝色"Python空间"关注我丫 加个"星标",每天一起快乐的学习 今 日 鸡 汤 名花倾国两相欢,常得君王带笑看. /前言/ 关于Python字符串格式化 ...

  4. python字符串format方法参数解释,一文秒懂!Python字符串格式化之format方法详解

    一文秒懂!Python字符串格式化之format方法详解 一文秒懂!Python字符串格式化之format方法详解 format是字符串内嵌的一个方法,用于格式化字符串.以大括号{}来标明被替换的字符 ...

  5. 【知识碎片】python 字符串格式化输出:%d,%s,%f

    在进行爬虫项目练习是会遇到语句中有%d,%s,%f的情况,这就是python字符串格式化输出.基本用法是将一个"值"插入到有字符串格式符%d,%s,%f的字符串中. 比如下面代码: ...

  6. python字符串格式化详解_Python字符串格式化%s%d%f详解

    Python字符串格式化%s%d%f详解 来源:中文源码网    浏览: 次    日期:2018年9月2日 [下载文档:  Python字符串格式化%s%d%f详解.txt ] (友情提示:右键点上 ...

  7. Python字符串格式化,%和format函数

    Python字符串格式化 格式化的操作有两种 一.使用%,常用的格式化 格式 描述 %s 字符串 %d 有符号整数(十进制) %f 浮点数 %O 转换为带符号的八进制形式的整数 %X 转换为带符号的十 ...

  8. Python字符串格式化%s输出

    Python 支持格式化字符串的输出 . 尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中. 在 Python 中,字符串格式化使用与 C 中 s ...

  9. python字符串格式化深入详解(四种方法)

    前言:本文详细整理了python字符串格式化的几种方式. 一.使用 % 符号来进行格式化 格式符为真实值预留位置,并控制显示的格式.格式符可以包含有一个类型码,用以控制显示的类型,如下: %s    ...

  10. 这篇文章有点长,但绝对是保姆级的Python字符串格式化讲解

    相关文件 想学Python的小伙伴可以关注小编的公众号[Python日志] 有很多的资源可以白嫖的哈,不定时会更新一下Python的小知识的哈!! Python学习交流群:773162165 前言 今 ...

最新文章

  1. TANDEM 基于深度多视图立体视觉的实时跟踪和稠密建图
  2. 看看40万程序猿怎么评论:对于程序员英语真的重要吗?
  3. 复仇者联盟与IntelliJ IDEA也很配哦
  4. 翻译 | 关键CSS和Webpack: 减少阻塞渲染的CSS的自动化解决方案
  5. VTK:可视化算法之CutWithCutFunction
  6. 如何建立程序代码包的联接?
  7. android edittext 不可编辑
  8. 添加功能与测试点总结
  9. 【Android车载系统 News | Tech 1】News 谷歌开发车载Android系统 2014-12-19
  10. 这家共享单车确认已坑12.5万用户 总金额超2512万元
  11. 四通滑阀非对称液压缸matlab,基于MATLAB-simulink的液压系统动态仿真PPT课件
  12. 配置案例|Modbus转Profinet网关连接英威腾Goodrive200A 的配置案例
  13. html如何解决412问题,html5-video – 如何修复412(前置条件失败)错误HTML5视频标记
  14. 基于python的博客设计与开发_基于python的博客设计与开发毕业设计
  15. html markdown写笔记,谈谈为知笔记的Markdown功能
  16. HBuilder X 无法启动微信开发者工具问题解决方法
  17. 线性代数可以做些什么?(之一)
  18. 提高转化率的 3 个客户引导最佳实践
  19. LANDESK DM桌面管理之客户端配置及部署篇
  20. SxSW机器人电视先生小组在节目中使用真实代码

热门文章

  1. 复现ICCV 2017经典论文—PyraNet
  2. Laplance算子(二阶导数)
  3. java毕业设计——基于java+JDBC+sqlserver的POS积分管理系统设计与实现(毕业论文+程序源码)——POS积分管理系统
  4. 【TWS使用系列1】如何从TWS的自选列表中添加/删除自选股?
  5. c语言汇率转换代码_拜求c语言编写的人民币大小写转换的代码!
  6. java gbk编码_Java GBK 中文乱码问题分析
  7. 【VS2015】Win7 X64上面安装VS2015
  8. python图形包是什么_介绍Python 图形计算工具包
  9. Elasticsearch最佳实践之使用场景
  10. 苹果6标准模式和放大模式具体有什么差别?