Python中必備的字串拼接方法,你知道多少?

2021-09-13 04:02:21 字數 2048 閱讀 6217

python拼接字串一般有以下幾種方法:

①直接通過(+)操作符拼接

s = 'hello'+' '+'world'+'!'

print(s)

輸出結果:hello world!

使用這種方式進行字串連線的操作效率低下,因為python中使用 + 拼接兩個字串時會生成乙個新的字串,生成新的字串就需要重新申請記憶體,當拼接字串較多時自然會影響效率。

②通過str.join()方法拼接

strlist=['hello',' ','world','!']

print(''.join(strlist))

輸出結果:hello world!

這種方式一般常使用在將集合轉化為字串,''.join()其中''可以是空字元,也可以是任意其他字元,當是任意其他字元時,集合中字串會被該字元隔開,例如:

​strlist=['hello',' ','world','!']

print(','.join(strlist))

輸出結果:hello, ,world,!

③通過str.format()方法拼接

s='{} {}!'.format('hello','world')

print(s)

輸出結果:hello world!

通過這種方式拼接字串需要注意的是字串中{}的數量要和format方法引數數量一致,否則會報錯。

④通過(%)操作符拼接

s = '%s %s!' % ('hello', 'world')

print(s)

輸出結果:hello world!

這種方式與str.format()使用方式基本一致。

⑤通過()多行拼接

s = (

'hello'

' ''world'

'!'

)

print(s)

輸出結果:hello world!

python遇到未閉合的小括號,自動將多行拼接為一行。

⑥通過string模組中的template物件拼接

from string import template

s = template('$ $!')

print(s.safe_substitute(s1='hello',s2='world'))

輸出結果:hello world!

template的實現方式是首先通過template初始化乙個字串。這些字串中包含了乙個個key。通過呼叫substitute或safe_subsititute,將key值與方法中傳遞過來的引數對應上,從而實現在指定的位置匯入字串。這種方式的好處是不需要擔心引數不一致引發異常,如:

from string import template

s = template('$ $ $!')

print(s.safe_substitute(s1='hello',s2='world'))

輸出結果:hello world $!

⑦通過f-strings拼接

在python3.6.2版本中,pep 498 提出一種新型字串格式化機制,被稱為「字串插值」或者更常見的一種稱呼是f-strings,f-strings提供了一種明確且方便的方式將python表示式嵌入到字串中來進行格式化:

s1='hello'

s2='world'

print(f' !')

輸出結果:hello world!

在f-strings中我們也可以執行函式:

def power(x):

return x*x
x=4

print(f' * = ')

輸出結果:4 * 4 = 16

而且f-strings的執行速度很快,比%-string和str.format()這兩種格式化方法都快得多。

原文:

Python中必備的字串拼接方法,你知道多少?

python拼接字串一般有以下幾種方法 s hello world print s 輸出結果 hello world 使用這種方式進行字串連線的操作效率低下,因為python中使用 拼接兩個字串時會生成乙個新的字串,生成新的字串就需要重新申請記憶體,當拼接字串較多時自然會影響效率。strlist h...

拼接字串 Python中字串拼接的N 1種方法

python拼接字串一般有以下幾種方法 1.直接通過 操作符拼接 輸出結果 hello world 使用這種方式進行字串連線的操作效率低下,因為python中使用 拼接兩個字串時會生成乙個新的字串,生成新的字串就需要重新申請記憶體,當拼接字串較多時自然會影響效率。2.通過str.join 方法拼接 ...

python 字串拼接

閱讀目錄 1.加號 2.逗號 3.直接連線 4.格式化 5.join 6.多行字串拼接 回到頂部 示例版本為py2 回到頂部 第一種,有程式設計經驗的人,估計都知道很多語言裡面是用加號連線兩個字串,python裡面也是如此直接用 來連線兩個字串 print python tab 結果 pythont...