python字串中的單雙引

2021-07-24 21:28:28 字數 1892 閱讀 1913

python中字串可以(且僅可以)使用成對的單引號、雙引號、三個雙引號(文件字串)包圍:

'this is a book'

"this is a book"

"""this is a book"""

可在單引號包圍的字串中包含雙引號,三引號等,但不能包含單引號自身(需轉義)

'this is a"

book'

'this is a"

" book'

'this is a"

""book'

'this is a\' book'

也可多單引號中的雙引號轉義,但通常沒什麼必要和意義

'this

is a\" book'

同理,雙引號中可包含單引號,但不能包含雙引號以及由雙引號構成的三引號

"this is a' book"

"this is a\" book"

也可對雙引號中的單引號進行轉義,但同樣,這通常沒有必要也沒有意義

"this is a\' book"
現在還有乙個問題,如果我想在單引號包圍的字串中顯示「\』」呢,答案是分別對「\」和「』」進行轉義,也即要想在字串中顯示「\」這個特殊字元,需對特殊字元本身進行轉義,其他特殊字元類似。

>>> s='this is a\' book'

>>> print s

this

is a' book

>>> s='

this

is a\\\' book'

>>> print s

this

is a\' book

要顯示多少次「\」就要對「\」進行多少次轉義:

>>> s='this is a\\\\\' book'

>>>

print s

this is a\\' book

同樣,想在雙引號包圍的字串中顯示「\」」也要分別對「\」和「」」進行轉義。

>>> s="this is a\\\" book"

>>>

print s

this is a\" book

說到這裡,有必要談一談字串中「\』」和「\」」的替換問題,也即字串本身是包含這樣的子串的,比如:

>>> s='this is a\\\' book'

>>> s

"this is a\\' book"

>>>

print s

this is a\' book

這裡的字串中包含「\』」這樣乙個子串,現在想把這個子串替換為「@@@」

>>> s=s.replace('\\\'','@@@')

>>> s

'this is a@@@ book'

>>>

print s

this is a@@@ book

也即在書寫將被替換的子串時,也需對特殊的字元進行轉義,s=s.replace(『\\」,』@@@』)中經轉義後,最終的字串中將被替換掉的子串為「\』」.

雙引號中含有特殊字元的子串的替換遵循同樣的原理。

另外需要注意的是,想要知道字串最終的樣子則應當使用print函式將其列印出來,以免混淆。

>>> s='this is a\\\' book'

>>> s

"this is a\\' book"

>>>

print s

this is a\' book

python中單 雙 三引號的區別

在 python中字串可以用單引號括起來,也可以用雙引號,這兩種方式是等價的,而在php當中單引號和雙引號的有些是不一樣的,雖然表示的字串,但是在php的單引號解析速度比雙引號快,如果在python用單號那麼在字串中就可以直接收寫雙引號了,反之亦然。這就是python為什麼允許用兩種方式的原因。在實...

python中的字串

方法1 用字串的join方法 a a b c d content content join a print content 方法2 用字串的替換佔位符替換 a a b c d content content s s s s tuple a print content 我們可以通過索引來提取想要獲取的...

python中的字串

b nihao hahah xixi 輸出 nihao nhahah nxixi n 原字串 big r this hhaha big輸出 this nhhaha 還原為unicode字串 hello u hello u0020world hello輸出 hello world 字串是不可以改變的 ...