您的位置:首页 > 编程语言 > Python开发

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
  • 收藏
  • 分享
  • 文章举报
知其然也 发布了5 篇原创文章 · 获赞 3 · 访问量 832 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: