python3.6【新特性:f-string】PEP 498: Formatted string literals

原文连接:https://blog.csdn.net/s740556472/article/details/81111493html

前言

用了这么久的python3.6,今天才知道竟然有了这么一个方便的特性,一块儿来看一下。java

官网资料

https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep498python

这里写图片描述

PEP 498 introduces a new kind of string literals: f-strings, or formatted string literals.
Formatted string literals are prefixed with ‘f’ and are similar to the format strings accepted by str.format(). They contain replacement fields surrounded by curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format() protocol:web

翻译以下:sql

格式化的字符串文字以“f”为前缀,相似于str.format()接受的格式字符串。它们包含由花括号包围的替换字段。替换字段是表达式,在运行时进行评估,而后使用format()协议进行格式化:express

工做原理:markdown

The expressions that are extracted from the string are evaluated in the context where the f-string appeared. This means the expression has full access to local and global variables. Any valid Python expression can be used, including function and method calls.app

翻译以下:curl

从字符串中提取的表达式在f字符串出现的上下文中计算。这意味着表达式能够彻底访问本地和全局变量。可使用任何有效的Python表达式,包括函数和方法调用。ide

与以前的方法对比

3.6以前,我最经常使用的方法是%-formatting,以前初学python时,也有总结过相应的用法:连接以下:
https://blog.csdn.net/s740556472/article/details/77823072
为何看到了新特性,以为很是开心呢?是由于这种老方式的冗余性,给你们看一个以前写过的python脚本,只是为了生成相应的sql语句,就须要拼装好多冗余的%号,以下:

sql = ("insert into student (" "id, name, gender, tall, weight)" "values(" " '%s', '%s', '%s', '%s', '%s');" %(id,name,gender,tall,weight)
       )

只有5个字段的表,都要写这么冗余的%s,因此一旦字段不少,那么发生字符串拼接的错误几率就会变大。这样看来并不友好。。。

新特性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 字符串用法很是好用,在性能上,在容错率上,在外观上,都是更上一层的!因此强力推荐。。。

额外连接好文

一篇外文:
https://realpython.com/python-f-strings/#multiline-f-strings
一篇国内翻译过来的好文章(可是其中翻译有的地方有误解):
http://www.mlln.cn/2018/05/19/python3%20f-string%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E9%AB%98%E7%BA%A7%E7%94%A8%E6%B3%95/