(那些過時的) Python 字串格式化以及 f-string 字串格式化
2018-03-22 14:27
435 查看
转自:https://blog.louie.lu/2017/08/08/outdate-python-string-format-and-fstring/
那啥,今天从网上看个代码,有一段在我本地编辑器(pycharm)显示错误
对,就是红色下划线。
我就纳闷了(以前没用过f'xxx' 的写法),百度下,没看懂,谷歌下,就找到上面那个
在 Python 裡頭,目前的最新版本 (3.6.2) 中總共有 3 種不同的方式來達成字串格式化 (String format)。分別是 %-formatting、str.format 以及 f-string。本文將會逐一介紹這些 Python 的字串格式化方式。
Python
從今天開始,忘了它。
Python
各種技巧請參考:Format Specification Mini-Language
從今天開始,忘了它。
Python
還可以這樣:
Python
從今天開始使用 f-string!
恩,就这样吧
那啥,今天从网上看个代码,有一段在我本地编辑器(pycharm)显示错误
对,就是红色下划线。
我就纳闷了(以前没用过f'xxx' 的写法),百度下,没看懂,谷歌下,就找到上面那个
在 Python 裡頭,目前的最新版本 (3.6.2) 中總共有 3 種不同的方式來達成字串格式化 (String format)。分別是 %-formatting、str.format 以及 f-string。本文將會逐一介紹這些 Python 的字串格式化方式。
01. %-formatting
偉大的 C 語言字串格式化深入我們的生活,Python 自然也不意外的會有這個功能。Python
1 2 3 4 5 6 | >>>'Python version: %.1f'% (3.6) 'Python version: 3.6' >>>'We have %d apple, %d banana'% (10,20) 'We have 10 apple, 20 banana' >>>'Hello, %s'% ('Denny') 'Hello Denny' |
02. str.format
PEP 3101 帶來了str.forma 4000 t(),讓我們可以用
.format的方式來格式化字串:
Python
1 2 3 4 5 6 7 8 9 10 11 | >>>'Python version: {:.5f}'.format(3.6) 'Python version: 3.60000' >>>'Hello {name:*^15}'.format(name='foobar') 'Hello ****foobar*****' >>>forbase in'dXob': ... print('{:{width}{base}}'.format(15,base=base,width=5)) ... 15 F 17 1111 |
從今天開始,忘了它。
03. f-string
PEP 498 帶來了 f-string,它的學名叫作 “Literal String Interpolation”。用法如下:Python
1 2 3 4 5 6 7 | >>>defupper(s): ... returns.upper() ... >>>stock= 'tsmc' >>>close= 217.5 >>>f'{stock} price: {close}' 'tsmc price: 217.5' |
Python
1 2 3 | >>>f'{upper(stock)} price: {close}' 'TSMC price: 217.5' >>> |
恩,就这样吧
相关文章推荐
- python中string模块各属性以及函数的用法介绍
- JSON.parse()和JSON.stringify()以及stringify()字符串格式化
- python输入,格式化输入,以及scanf的替代方案
- python(5): string的格式化输出
- Python零基础入门之五字符串的格式化以及序列的内置函数
- 牛人总结python中string模块各属性以及函数的用法,果断转了,好东西
- String转换为JSON以及时间的格式化
- Python中数据类型变量,编码以及格式化注意细节O(∩_∩)O
- python中string模块各属性以及函数的用法
- [python学习笔记] String格式化
- python 获取前一天日期以及字符串的格式化
- Python 字符串 string.format() 格式化方法
- Python字符串的连接、替换、截取,以及字符串格式化输出,引号
- python中string模块各属性以及函数的用法
- python基础之常用模块以及格式化输出
- 收集那些奇怪的Python语句以及写法
- python常用的字串格式化选项
- python 字串格式化选项
- Python F-string 更快的格式化
- Python第三天——字符串的格式化、转义以及深浅复制