365速发国际靠谱么-365_体育投注英超和欧冠-365bet主页器

python字符串前加 f 的含义

python字符串前加 f 的含义

字符串前加 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及以后的版本可用。

相关推荐