python字符串前加 f 的含义
2020-02-17 04:14
477 查看
字符串前加 f 的含义
副标题: f-string 概述
官方文档:点击这里
如果你今天将就而选择参考了我的文档,总有一天你还是会去阅读官方文档。
先看例子
list_ = [1,2,3] print(list_, f'has a length of {len(list_)}.') # [1,2,3] has a length of 3.
看懂这个例子,用法也基本掌握了。
用法
官方文档:
Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
大概意思就是:
格式化 {} 内容,不在 {} 内的照常展示输出,如果你想输出 {},那就用双层 {{}} 将想输出的内容包起来。
效果如下:
list_ = [1,2,3] print(list_, f'has a length of {len(list_)}.') # [1,2,3] has a length of 3. print(list_, f'has a length of {{len(list_)}}.') # [1,2,3] has a length of {len(list_)}. print(list_, f'has a length of {{{len(list_)}}}.') # [1,2,3] has a length of {3}.
总结
f-string: formatted string literals, 格式化字符串常量。
功能同str.format() %-formatting,
较两者更简洁易用,推荐使用
需要注意的是,Python3.6及以后的版本可用。
- 点赞 1
- 收藏
- 分享
- 文章举报
相关文章推荐
- Python中 IOError 和 FileNotFoundError
- Python-List
- Python-List-Append
- Python-List-extend
- Python-List-Pop
- Python-List-sort
- 关于pycharm用不了numpy
- 零基础学Python
- PAT 1010 一元多项式求导 Python实现
- 最长回文子串(python实现)
- 整数反转(Python实现)
- python基础(一)
- python爬虫-1
- python中random模块
- Python之__str__类的特殊方法
- python中的__slots__
- Python中面向对象的__init__,__new__方法剖析
- python中的四种单例模式
- 贝叶斯定理_python实现_1_贝叶斯基础
- numpy实现分段函数