字符串前加r
r""作用是非轉(zhuǎn)義的原始字符串,原意輸出。
相對(duì)特殊的字符,其中可能包含轉(zhuǎn)義字符,反斜杠加上對(duì)應(yīng)字母,表示對(duì)應(yīng)的特殊含義的【"\n","\t"】。
以r開頭的字符,常用于正則表達(dá)式,對(duì)應(yīng)re模塊。
例子:
a = "Hello\nWorld"
b = r"Hello\nWorld"
print(a)
print(b)
輸出
Hello
World
Hello\nWorld
字符串前加b
b"" 的作用是后面的字符串會(huì)轉(zhuǎn)為bytes類型。
用處:網(wǎng)絡(luò)編程中,服務(wù)器和瀏覽器只認(rèn)bytes 類型數(shù)據(jù)。
例子:
a = "hello world"
b = b"hello world"
print(a,type(a))
print(b,type(b))
print("----------")
#二進(jìn)制和字符串之間相互轉(zhuǎn)換
print(a.encode("utf-8"),type(a.encode("utf-8")))
print(b.decode("utf-8"),type(b.decode("utf-8")))
輸出
hello world <class 'str'>
b'hello world' <class 'bytes'>
----------
b'hello world' <class 'bytes'>
hello world <class 'str'>
字符串前加 u
不是僅僅是針對(duì)中文, 可以針對(duì)任何的字符串,代表是對(duì)字符串進(jìn)行unicode編碼。
一般英文字符在使用各種編碼下, 基本都可以正常解析, 所以一般不帶u;但是中文, 必須表明所需編碼, 否則一旦編碼轉(zhuǎn)換就會(huì)出現(xiàn)亂碼。
建議所有編碼方式采用utf8.
字符串前加 f
f"" 格式化操作,相當(dāng)于format()函數(shù).
例子
name = "張三"
print(f"{name}")
輸出
張三