8種Python字符串拼接的方法,你知道幾種?


一、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


免責聲明!

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



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