Python字符串拼接之 f-string 详解

1,416 阅读3分钟

一、字符串拼接方法

1. +

str1 = 'a'
str2 = 'b'
print(str1 + str2)

输出:

ab

2. ,

str1 = 'a'
str2 = 'b'
print(str1, str2)

输出:

a b

注: 这个有空格,, 方法只能用于 print 函数。

3. %

str1 = 'a'
str2 = 'b'
print('%s%s' % (str1, str2))

输出:

ab

4. *

str1 = 'a'
print(str1 * 3)

输出:

aaa

5. str.format()

str1 = 'a'
str2 = 'b'
print('{}{}'.format(str1, str2))

输出:

ab

注: Python 2.6 中出现。

6. join

str1 = 'a'
str2 = 'b'
print('-'.join([str1, str2]))

输出:

a-b

注: str1 和 str2 拼接在 - 左右。

7. f-string

str1 = 'a'
str2 = 'b'
str = f'this is str1: {str1}, this is str2: {str2}.'
print(str)

输出:

this is str1: a, this is str2: b.

二、f-string 详解

f-string 是 Python 3.6 之后加入标准库的。PEP 498 中有详细介绍。其中有这样一段话:

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.

说明 f-string 比 %-formattingstr.format() 都快。因为 f-string 是运行时渲染的表达式,而不是常量值。

1. 简单用法

name = "Eric"
age = 74
res = f"Hello, {name}. You are {age}."
print(res)

输出:

Hello, Eric. You are 74.

2. 表达式

res = f"{2 * 37}"
print(res)

输出:

74

3. 函数

res = f"{name.lower()} is funny."
print(res)

输出:

eric is funny.

4. 多行 f-string

profession = "comedian"
affiliation = "Monty Python"
message = (f"Hi {name}. "
        "You are a {profession}. "
        "You were in {affiliation}.")
print(message)

输出:

Hi Eric. You are a {profession}. You were in {affiliation}.

这时候需要使用 """

message = f"""
    Hi {name}. 
    You are a {profession}. 
    You were in {affiliation}.
 """
print(message)

输出:

Hi Eric. 
You are a comedian. 
You were in Monty Python.

5. 引号

确保在表达式中使用的 f-string 外部没有使用相同类型的引号即可。

简单来说就是,外部使用了 "",内部只能使用 ''。另外,如果外部使用了一个 '',会发现内部多行的话需要单独写换行符号 \,例如:

main_sql = f'select role, \
        day \
    from xxx'
print(main_sql)

不写 \ 会报错:

SyntaxError: EOL while scanning string literal

因此一个比较好的方法是外部使用 """,这样内部引号 '' 不需要转义,而且多行也不需要写换行符号。

main_sql = f"""select role,
        day
    from xxx"""
print(main_sql)

输出:

select role,
        day
    from xxx

6. 字典

如果要为字典的键使用单引号,请记住确保对包含键的 f-string 使用双引号。

comedian = {'name': 'Eric Idle', 'age': 74}
res = f"The comedian is {comedian['name']}, aged {comedian['age']}."
print(res)

输出:

The comedian is Eric Idle, aged 74.

所以最好外部引号直接用 """,就不用担心那么多问题了。

7. 大括号

为了使字符串出现大括号,必须使用双大括号:

res = f"{{74}}"
print(res)

输出:

{74}

8. 转义

可以在 f-string 的字符串部分使用反斜杠转义符。但是,不能使用反斜杠在 f-string 的表达式部分中进行转义:

res = f"{\"Eric Idle\"}"
print(res)

报错:

SyntaxError: f-string expression part cannot include a backslash

下面这种是可以的:

res = f"The \"comedian\" is {name}, aged {age}."
print(res)

输出:

The "comedian" is Eric, aged 74.

9. lambda表达式

如果 !, :} 不在括号,大括号或字符串中,则它将被解释为表达式的结尾。由于lambda使用 ,这可能会导致一些问题:

res = f"{lambda x: x * 37 (2)}"
print(res)

报错:

SyntaxError: unexpected EOF while parsing

下面这种是可以的:

res = f"{(lambda x: x * 37) (2)}"
print(res)

输出:

74

三、总结

- 适合少量短的字符串拼接。

f-string 适合大量字符串拼接,而且在变量比较多的情况下可读性较高。

四、参考

PEP 498 -- Literal String Interpolation

python3 f-string格式化字符串的高级用法

可能是最全面的 python 字符串拼接总结