IT科技

當前位置 /首頁/IT科技 > /列表

字符串連接,python

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'>