Python中四個(gè)最實(shí)用的字符串方法完全指南
摘要
字符串是 Python 中最常用的數(shù)據(jù)類型,本文詳細(xì)介紹四個(gè)最實(shí)用的字符串方法:split 分割、join 拼接、strip 去除空白、replace 替換。掌握這些方法,讓你處理文本效率翻倍
1. 概述
在 Python 中,字符串無(wú)處不在,處理文本數(shù)據(jù)是每個(gè)程序員的必備技能。本文介紹的四個(gè)方法是最常用的字符串處理工具,幾乎每個(gè)項(xiàng)目都會(huì)用到
2. 分割:split 方法
split 是 Python 字符串中最常用的分割方法,可以把一個(gè)字符串按照分隔符拆分成列表 ??
2.1 基本用法
什么是空白字符?
空白字符(Whitespace)是不可見的,但不可見的字符不一定都是空白字符:
| 類型 | 例子 |
|---|---|
| 空白字符 | 空格、制表符(\t)、換行(\n)、回車(\r)、換頁(yè)符(\f) |
| 其他不可見字符 | 零寬空格、BOM 標(biāo)記等 |
簡(jiǎn)單說(shuō):空白字符是不可見字符的一個(gè)子集。
按空白字符分割(默認(rèn))
不指定分隔符時(shí),會(huì)按任意空白字符分割:
text = "hello world python" result = text.split() print(result) # ['hello', 'world', 'python'] # 多個(gè)空格也會(huì)自動(dòng)處理 text2 = "hello world" print(text2.split()) # ['hello', 'world']
按指定分隔符分割
text = "apple,banana,orange"
result = text.split(',')
print(result) # ['apple', 'banana', 'orange']
2.2 限制分割次數(shù)
使用 maxsplit 參數(shù)可以限制分割次數(shù):
text = "a,b,c,d,e"
# 只分割1次
print(text.split(',', 1)) # ['a', 'b,c,d,e']
# 只分割2次
print(text.split(',', 2)) # ['a', 'b', 'c,d,e']
2.3 實(shí)際應(yīng)用
處理 CSV 數(shù)據(jù)
line = "name,age,city"
fields = line.split(',')
print(fields) # ['name', 'age', 'city']
解析 URL 參數(shù)
url = "https://example.com?name=john&age=25"
query = url.split('?')[1] # 取?后面的部分
params = query.split('&')
print(params) # ['name=john', 'age=25']
按行分割
text = "line1\nline2\nline3"
lines = text.split('\n')
print(lines) # ['line1', 'line2', 'line3']
3. 拼接:join 方法
join 是 Python 中最高效的字符串拼接方法,可以把列表、元組、集合、生成器等任何可迭代對(duì)象的元素連接成一個(gè)字符串(但元素必須是字符串類型)
3.1 基本用法
拼接列表
words = ['hello', 'world', 'python'] # 用空格連接 result = ' '.join(words) print(result) # hello world python # 用逗號(hào)連接 result = ','.join(words) print(result) # hello,world,python # 用空字符串連接 result = ''.join(words) print(result) # helloworldpython
拼接元組
words = ('apple', 'banana', 'orange')
result = ' - '.join(words)
print(result) # apple - banana - orange
3.2 注意事項(xiàng)
元素必須是字符串
# 數(shù)字列表會(huì)報(bào)錯(cuò) nums = [1, 2, 3] # ' '.join(nums) # TypeError! # 需要先轉(zhuǎn)換 nums = [1, 2, 3] result = ' '.join(str(n) for n in nums) print(result) # 1 2 3
3.3 實(shí)際應(yīng)用
構(gòu)建文件路徑
parts = ['folder', 'subfolder', 'file.txt'] path = '/'.join(parts) print(path) # folder/subfolder/file.txt
生成 URL 查詢字符串
params = ['name=john', 'age=25', 'city=beijing'] query = '&'.join(params) print(query) # name=john&age=25&city=beijing
CSV 數(shù)據(jù)拼接
fields = ['name', 'age', 'city'] csv_line = ','.join(fields) print(csv_line) # name,age,city
3.4 為什么 join 更高效?
知道了解就好,不用深究
相比用 + 拼接多個(gè)字符串,join 只需要分配一次內(nèi)存:
# 低效:每次拼接都會(huì)創(chuàng)建新字符串
result = ''
for word in words:
result += word # 每次都分配新內(nèi)存
# 高效:一次性拼接
result = ''.join(words) # 只分配一次內(nèi)存
4. 去除空白:strip 方法
strip 用于去除字符串首尾的空白字符(空格、換行、制表符等)
4.1 基本用法
text = " hello world " print(text.strip()) # hello world # 換行符 text = "\nhello\n" print(text.strip()) # hello # 制表符 text = "\thello\t" print(text.strip()) # hello
4.2 變體方法
| 方法 | 說(shuō)明 | 例子 |
|---|---|---|
strip() | 去除兩端 | " hello " → "hello" |
lstrip() | 去除左側(cè) | " hello" → "hello" |
rstrip() | 去除右側(cè) | "hello " → "hello" |
text = " hello world " print(text.lstrip()) # hello world (去左邊) print(text.rstrip()) # hello world (去右邊)
4.3 去除指定字符
可以指定要去除的字符:
text = "---hello---"
print(text.strip('-')) # hello
text = "++hello++"
print(text.strip('+')) # hello
# 多個(gè)字符
text = "abchelloabc"
print(text.strip('abc')) # hello
注意:strip('abc') 會(huì)從兩端依次去掉 a、b、c 這三個(gè)字符,遇到其他字符就停止(不是去掉子串 "abc")
4.4 實(shí)際應(yīng)用
處理用戶輸入
username = " john " username = username.strip() print(username) # john
讀取文件行
lines = [" line1 ", "line2\n", " line3 "] cleaned = [line.strip() for line in lines] print(cleaned) # ['line1', 'line2', 'line3']
5. 替換:replace 方法
replace 用于替換字符串中的子串
5.1 基本用法
text = "hello world"
result = text.replace("world", "python")
print(result) # hello python
5.2 替換次數(shù)
使用 count 參數(shù)可以限制替換次數(shù):
text = "aaa bbb aaa ccc aaa"
# 默認(rèn):替換所有
print(text.replace("aaa", "xxx")) # xxx bbb xxx ccc xxx
# 只替換前1次
print(text.replace("aaa", "xxx", 1)) # xxx bbb aaa ccc aaa
# 只替換前2次
print(text.replace("aaa", "xxx", 2)) # xxx bbb xxx ccc aaa
5.3 注意事項(xiàng)
大小寫敏感
text = "Hello hello HELLO"
print(text.replace("hello", "hi")) # Hello hi HELLO(只替換小寫的)
5.4 實(shí)際應(yīng)用
敏感詞過濾
text = "這個(gè)產(chǎn)品太垃圾了,太差了"
filtered = text.replace("垃圾", "**").replace("差", "*")
print(filtered) # 這個(gè)產(chǎn)品太**了,太*了
格式化數(shù)據(jù)
data = "name:john, age:25, city:beijing"
result = data.replace(", ", "\n")
print(result)
# name:john
# age:25
# city:beijing
6. 總結(jié)
這篇文章我們學(xué)習(xí)了 Python 字符串的四個(gè)常用方法
方法對(duì)比
| 方法 | 作用 | 例子 |
|---|---|---|
split | 字符串→列表 | "a,b".split(',') → ['a', 'b'] |
join | 列表→字符串 | ['a', 'b'].join(',') → "a,b" |
strip | 去除空白 | " hi ".strip() → "hi" |
replace | 替換子串 | "hi boy".replace('boy', 'girl') → "hi girl" |
使用建議
- 分割/拼接:處理 CSV、數(shù)據(jù)清洗用
split+join - 去除空白:處理用戶輸入、文件行用
strip - 替換:敏感詞過濾、數(shù)據(jù)格式化用
replace
這四個(gè)方法是字符串處理的基石,熟練掌握能讓你處理文本效率翻倍!
以上就是Python中四個(gè)最實(shí)用的字符串方法完全指南的詳細(xì)內(nèi)容,更多關(guān)于Python最實(shí)用的字符串方法的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python結(jié)合shell自動(dòng)創(chuàng)建kafka的連接器實(shí)戰(zhàn)教程
這篇文章主要介紹了python結(jié)合shell自動(dòng)創(chuàng)建kafka的連接器,需要安裝連接oracle的python包,獲取oracle表信息,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
記一次pyinstaller打包pygame項(xiàng)目為exe的過程(帶圖片)
這篇文章主要介紹了記一次pyinstaller打包pygame項(xiàng)目為exe的過程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Selenium定時(shí)刷新網(wǎng)頁(yè)的實(shí)現(xiàn)代碼
這篇文章主要介紹了Selenium定時(shí)刷新網(wǎng)頁(yè)的實(shí)現(xiàn)代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-10-10
對(duì)python:print打印時(shí)加u的含義詳解
今天小編就為大家分享一篇對(duì)python:print打印時(shí)加u的含義詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-12-12
Python統(tǒng)計(jì)時(shí)間內(nèi)的并發(fā)數(shù)代碼實(shí)例
這篇文章主要介紹了Python統(tǒng)計(jì)時(shí)間內(nèi)的并發(fā)數(shù)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
python學(xué)習(xí)教程之socket庫(kù)的基本使用(網(wǎng)絡(luò)編程-套接字)
Python中的socket模塊提供了網(wǎng)絡(luò)編程中的套接字(socket)功能,通過套接字我們可以實(shí)現(xiàn)不同計(jì)算機(jī)之間的通信,這篇文章主要給大家介紹了關(guān)于python學(xué)習(xí)教程之socket庫(kù)的基本使用,需要的朋友可以參考下2024-07-07
python unittest實(shí)現(xiàn)api自動(dòng)化測(cè)試
這篇文章主要為大家詳細(xì)介紹了python unittest實(shí)現(xiàn)api自動(dòng)化測(cè)試的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04

