Python中f-string用法
单行f
先使用官网以及自己测试的小例子来说明使用方法:代码如下:
使用方法: f’{}’
这种写法比较像java中的el表达式,也是采用了大括号的形式进行读取!
coding = utf-8
“”"
@author: sy
@file: test_f_string.py
@time: 2018/7/19 10:44
@desc: 测试f字符串新特性
“”"
def main():
name = "Fred"
print(f'He said his name is {name}.')
def sum_a_b(a, b):
return a + b
if __name__ == '__main__':
main()
a = 1
b = 3
print('求和的结果为:' + f'{sum_a_b(a,b)}')
看下结果图:
多行f
有时候字符串会拼接很长,所以可以折成多行去做处理
代码如下:
def more_line():
name = 'lisi'
age = 12
ajd = 'handsome'
speaker = f"Hi {name}. " \
f"You are {age} years old. " \
f"You are a {ajd} guy!"
效果图如下:
性能
f字符串中的f也可以代表“速度快”。
“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with f, which contains expressions inside braces. The expressions are replaced with their values.” (Source)
翻译:
“f -string提供了一种方法,可以在字符串文字中嵌入表达式,使用最小的语法。”应该注意的是,f-string实际上是在运行时计算的表达式,而不是一个常量值。在Python源代码中,f-string是一个文本字符串,前缀为f,其中包含括号内的表达式。表达式被替换为它们的值。”(来源)
总结
总而言之,就是python3.6的 f 字符串用法非常好用,在性能上,在容错率上,在外观上,都是更上一层