當前位置:生活全書館 >

IT科技

> 字串連線 python

字串連線 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'>

  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/vpykmv.html