Python學習筆記:字符串連接(join、os.path.join)


一、join函數

join 是 python 中字符串自帶的一個方法,返回一個字符串。使用語法為:

sep.join(可迭代對象) --》 str
# sep 分隔符 可以為空

將一個包含多個字符串的可迭代對象(字符串、元組、列表),轉為用分隔符sep連接的字符串。

  • 列表

列表必須為非嵌套列表,列表元素為字符串(str)類型

list1 = ["123", "456", "789"]
''.join(list1) # '123456789'
'-'.join(list1) # '123-456-789'
  • 元組
tuple1 = ('abc', 'dd', 'ff')
''.join(tuple1) # 'abcddff'
'*'.join(tuple1) # 'abc*dd*ff'
  • 字符串
str1 = "hello Hider"
''.join(str1)
':'.join(str1)
# 'h:e:l:l:o: :H:i:d:e:r'
  • 字典

默認拼接 key 的列表,取 values 之后拼接值。

dict1 = {"a":1, "b":2, "c":3}
''.join(dict1) # 'abc'
'*'.join(dict1) # 'a*b*c'
# 拼接的是key

# 值也必須是字符才可以拼接
dict1 = {"a":1, "b":2, "c":3}
'*'.join(str(dict1.values()))
# 'd*i*c*t*_*v*a*l*u*e*s*(*[*1*,* *2*,* *3*]*)' 否則

二、os.path.join函數

os.path.join函數將多個路徑組合后返回,使用語法為:

os.path.join(path1 [,path2 [,...]])

注:第一個絕對路徑之前的參數將被忽略

# 合並目錄
import os
os.path.join('/hello/', 'good/boy/', 'Hider')
# '/hello/good/boy/Hider'

三、“+” 號連接

最基本的方式就是使用 “+” 號連接字符串。

text1 = "Hello"
text2 = "Hider"
text1 + text2 # 'HelloHider'

該方法性能差,因為 Python 中字符串是不可變類型,使用“+”號連接相當於生成一個新的字符串,需要重新申請內存,當用“+”號連接非常多的字符串時,將會很耗費內存,可能造成內存溢出。

四、“,”連接成tuple(元組)類型

使用逗號“,”連接字符串,最終會變成 tuple 類型。

text1 = "Hello"
text2 = "Hider"
text1 , text2 # ('Hello', 'Hider')
type((text1, text2)) # tuple

五、“%s”占位符 or format連接

借鑒C語言中的 printf 函數功能,使用%號連接一個字符串和一組變量,字符串中的特殊標記會被自動使用右邊變量組中的變量替換。

text1 = "Hello"
text2 = "Hider"
"%s%s" % (text1, text2) # 'HelloHider'

使用 format 格式化字符串也可以進行拼接。

text1 = "Hello"
text2 = "Hider"
"{0}{1}".format(text1, text2) # 'HelloHider'

六、空格自動連接

"Hello" "Hider" # 'HelloHider'

不支持使用參數代替具體的字符串,否則報錯。

七、“*” 號連接

這種連接方式相當於 copy 字符串,例如:

text1 = "Hider"
text1 * 5 # 'HiderHiderHiderHiderHider'

八、多行字符串連接()

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

text = ('666'
        '555'
        '444'
        '333')
print(text) # 666555444333
print(type(text)) # <class 'str'>

參考鏈接1:python中join的使用

參考鏈接2:Python join() 函數 連接字符串

參考鏈接3:聊聊 Python 字符串連接的七種方式

參考鏈接4:Python 拼接字符串的幾種方式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM