一竣稽、字符串拼接方法
1. +
str1 = 'a'
str2 = 'b'
print(str1 + str2)
輸出:
ab
2. ,
str1 = 'a'
str2 = 'b'
print(str1, str2)
輸出:
a b
注:這個有空格越驻,,
方法只能用于 print
函數(shù)肴茄。
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 中出現(xiàn)拣技。
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 之后加入標(biāo)準(zhǔn)庫的。PEP 498 中有詳細(xì)介紹彻舰。其中有這樣一段話:
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 比 %-formatting
和 str.format()
都快伐割。因為 f-string 是運行時渲染的表達(dá)式,而不是常量值刃唤。
1. 簡單用法
name = "Eric"
age = 74
res = f"Hello, {name}. You are {age}."
print(res)
輸出:
Hello, Eric. You are 74.
2. 表達(dá)式
res = f"{2 * 37}"
print(res)
輸出:
74
3. 函數(shù)
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. 引號
確保在表達(dá)式中使用的 f-string 外部沒有使用相同類型的引號即可隔心。
簡單來說就是,外部使用了 ""
尚胞,內(nèi)部只能使用 ''
硬霍。另外,如果外部使用了一個 ''
笼裳,會發(fā)現(xiàn)內(nèi)部多行的話需要單獨寫換行符號 \
唯卖,例如:
main_sql = f'select role, \
day \
from xxx'
print(main_sql)
不寫 \
會報錯:
SyntaxError: EOL while scanning string literal
因此一個比較好的方法是外部使用 """
,這樣內(nèi)部引號 ''
不需要轉(zhuǎn)義躬柬,而且多行也不需要寫換行符號拜轨。
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.
所以最好外部引號直接用 """
橄碾,就不用擔(dān)心那么多問題了。
7. 大括號
為了使字符串出現(xiàn)大括號昧廷,必須使用雙大括號:
res = f"{{74}}"
print(res)
輸出:
{74}
8. 轉(zhuǎn)義
可以在 f-string 的字符串部分使用反斜杠轉(zhuǎn)義符堪嫂。但是,不能使用反斜杠在 f-string 的表達(dá)式部分中進(jìn)行轉(zhuǎn)義:
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表達(dá)式
如果 !, :
或 }
不在括號木柬,大括號或字符串中皆串,則它將被解釋為表達(dá)式的結(jié)尾。由于lambda使用 :
眉枕,這可能會導(dǎo)致一些問題:
res = f"{lambda x: x * 37 (2)}"
print(res)
報錯:
SyntaxError: unexpected EOF while parsing
下面這種是可以的:
res = f"{(lambda x: x * 37) (2)}"
print(res)
輸出:
74
三恶复、總結(jié)
-
適合少量短的字符串拼接怜森。
f-string 適合大量字符串拼接,而且在變量比較多的情況下可讀性較高谤牡。