網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

字元串連接|python

欄目: IT科技 / 發佈於: / 人氣:2.39W

python中字元串怎麼連接呢?不知道的小夥伴來看看小編今天的分享吧!

python中字元串連接有七種方法。

方法一:用“+”號連接

用 “+”連接字元串是最基本的方式,代碼如下。

>>> text1 = "Hello"

>>> text2 = "World"

>>> text1 + text2 

'HelloWorld'

python 字元串連接

方法二:用“,”連接成 tuple (元組)類型

Python 中用“,”連接字元串,最終會變成 tuple 類型,代碼如下:

>>> text1 = "Hello"

>>> text2 = "World"

>>> text1 , text2 

('Hello','World')

>>> type((text1, text2))

<type 'tuple'>

>>>

方法三:用%s 佔位符連接

%s 佔位符連接功能強大,借鑑了C語言中 printf 函數的功能,這種方式用符號“%”連接一個字元串和一組變量,字元串中的特殊標記會被自動用右邊變量組中的變量替換:

>>> text1 = "Hello"

>>> text2 = "World"

>>> "%s%s"%(text1,text2)

'HelloWorld'

方法四:空格自動連接

>>> "Hello" "Nasus"

'HelloNasus'

值得注意的是,不能直接用參數代替具體的字元串,否則報錯,代碼如下:

>>> text1="Hello"

>>> text2="World"

>>> text1 text2

File "<stdin>", line 1

text1 text2

^

SyntaxError: invalid syntax

方法五:用“*” 連接

這種連接方式就是相當於 copy 字元串,代碼如下:

>>> text1="nasus "

>>> text1*4

'nasus nasus nasus nasus '

>>>

python 字元串連接 第2張

方法六:join 連接

利用字元串的函數 join。這個函數接受一個列表或元組,然後用字元串依次連接列表中每一個元素:

>>> list1 = ['P', 'y', 't', 'h', 'o', 'n']

>>> "".join(list1)

'Python'

>>>

>>> tuple1 = ('P', 'y', 't', 'h', 'o', 'n')

>>> "".join(tuple1)

'Python'

每個字元之間加 “|”

>>> list1 = ['P', 'y', 't', 'h', 'o', 'n']

>>> "|".join(list1)

'P|y|t|h|o|n'

方法七: 多行字元串拼接 ()

Python 遇到未閉合的小括號,自動將多行拼接爲一行,相比三個引號和換行符,這種方式不會把換行符、前導空格當作字元。

>>> text = ('666'

 '555'

 '444'

 '333')

>>> print(text)

666555444333

>>> print (type(text))

<class 'str'>