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


一、字符串拼接方法

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 字符串拼接總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM