一、join函式
join 是 python 中字串自帶的一個方法,回傳一個字串,使用語法為:
sep.join(可迭代物件) --》 str
# sep 分隔符 可以為空
將一個包含多個字串的可迭代物件(字串、元組、串列),轉為用分隔符sep連接的字串,
串列
串列必須為非嵌套串列,串列元素為字串(str)型別
list1 = ["123", "456", "789"]
print(''.join(list1)) # '123456789'
print('-'.join(list1)) # '123-456-789'
元組
#Python學習交流群:531509025
tuple1 = ('abc', 'dd', 'ff')
print(''.join(tuple1)) # 'abcddff'
print('*'.join(tuple1)) # 'abc*dd*ff'
字串
str1 = "hello Hider"
print(''.join(str1))
print(':'.join(str1))
# 'h:e:l:l:o: :H:i:d:e:r'
字典
默認拼接 key 的串列,取 values 之后拼接值,
dict1 = {"a":1, "b":2, "c":3}
print(''.join(dict1)) # 'abc'
print('*'.join(dict1)) # 'a*b*c'
# 拼接的是key
# 值也必須是字符才可以拼接
dict1 = {"a":1, "b":2, "c":3}
print('*'.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
print(os.path.join('/hello/', 'good/boy/', 'Hider'))
# '/hello/good/boy/Hider'
三、+ 號連接
最基本的方式就是使用 “+” 號連接字串,
text1 = "Hello"
text2 = "Hider"
print(text1 + text2) # 'HelloHider'
該方法性能差,因為 Python 中字串是不可變型別,使用“+”號連接相當于生成一個新的字串,需要重新申請記憶體,當用“+”號連接非常多的字串時,將會很耗費記憶體,可能造成記憶體溢位,
四、,連接成tuple(元組)型別
使用逗號“,”連接字串,最侄訓變成 tuple 型別,
#Python學習交流群:531509025
text1 = "Hello"
text2 = "Hider"
print(text1 , text2) # ('Hello', 'Hider')
print(type((text1, text2))) # <class 'tuple'>
五、%s占位符 or format連接
借鑒C語言中的 printf 函式功能,使用%號連接一個字串和一組變數,字串中的特殊標記會被自動使用右邊變陣列中的變數替換,
text1 = "Hello"
text2 = "Hider"
print("%s%s" % (text1, text2)) # 'HelloHider'
使用 format 格式化字串也可以進行拼接,
text1 = "Hello"
text2 = "Hider"
print("{0}{1}".format(text1, text2)) # 'HelloHider'
六、空格自動連接
print("Hello" "Hider")# 'HelloHider'
不支持使用引數代替具體的字串,否則報錯,
七、*號連接
這種連接方式相當于 copy 字串,例如:
text1 = "Hider"
print(text1 * 5) # 'HiderHiderHiderHiderHider'
八、多行字串連接()
Python遇到未閉合的小括號,自動將多行拼接為一行,相比3個引號和換行符,這種方式不會把換行符、前導空格當作字符,
text = ('666'
'555'
'444'
'333')
print(text) # 666555444333
print(type(text)) # <class 'str'>
結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!
Python基礎入門教程推薦:更多Python視頻教程-關注B站:Python學習者
https://www.bilibili.com/video/BV1LL4y1h7ny?share_source=copy_web
Python爬蟲案例教程推薦:更多Python視頻教程-關注B站:Python學習者
https://www.bilibili.com/video/BV1QZ4y1N7YA?share_source=copy_web
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/333246.html
標籤:Python
