欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python字符串格式化的3种方法

Python基础 迷途小书童 4年前 (2020-03-18) 5772次浏览 0个评论

软硬件环境

  • Windows 10 64bit
  • Anaconda with python 3.7.4

视频看这里

此处是youtube的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。

前言

Python里,目前总共有3种不同的方式来进行字符串的格式化(String format)。分別是%-formattingstr.format以及 f-string。本文将会逐一介绍这些Python的字符串格式化方法。

方法一

%-formatting这种写法来源于古老的C语言,很多从C语言转过来的人比较适应这种写法

PS C:\> ipython3.exe
Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.11.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 'Hello %s' % ('Python')
Out[1]: 'Hello Python'

In [2]: 'Hello Python%.1f' % (3.7)
Out[2]: 'Hello Python3.7'

方法二

PEP 3101带来了str.format(),让我们可以用.format的方式来格式化字符串

PS C:\> ipython3.exe
Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.11.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 'Hello Python {}'.format(3.7)
Out[1]: 'Hello Python 3.7'

方法三

Python 3.6开始,PEP 498带来了f-string,它的学名叫作"Literal String Interpolation"。f-string是格式化字符串的一种很好的新方法。与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快!推荐大家使用这种方法。

PS C:\> ipython3.exe
Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.11.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: py = 'Python'

In [2]: f'Hello {py}'
Out[2]: 'Hello Python'

参考资料

喜欢 (0)

您必须 登录 才能发表评论!