W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
你想去掉文本字符串開頭,結尾或者中間不想要的字符,比如空白。
strip()
方法能用于刪除開始或結尾的字符。lstrip()
和 rstrip()
分別從左和從右執(zhí)行刪除操作。默認情況下,這些方法會去除空白字符,但是你也可以指定其他字符。比如:
>>> # Whitespace stripping
>>> s = ' hello world \n'
>>> s.strip()
'hello world'
>>> s.lstrip()
'hello world \n'
>>> s.rstrip()
' hello world'
>>>
>>> # Character stripping
>>> t = '-----hello====='
>>> t.lstrip('-')
'hello====='
>>> t.strip('-=')
'hello'
>>>
這些 strip()
方法在讀取和清理數(shù)據(jù)以備后續(xù)處理的時候是經(jīng)常會被用到的。比如,你可以用它們來去掉空格,引號和完成其他任務。
但是需要注意的是去除操作不會對字符串的中間的文本產(chǎn)生任何影響。比如:
>>> s = ' hello world \n'
>>> s = s.strip()
>>> s
'hello world'
>>>
如果你想處理中間的空格,那么你需要求助其他技術。比如使用 replace()
方法或者是用正則表達式替換。示例如下:
>>> s.replace(' ', '')
'helloworld'
>>> import re
>>> re.sub('\s+', ' ', s)
'hello world'
>>>
通常情況下你想將字符串strip操作和其他迭代操作相結合,比如從文件中讀取多行數(shù)據(jù)。如果是這樣的話,那么生成器表達式就可以大顯身手了。比如:
with open(filename) as f:
lines = (line.strip() for line in f)
for line in lines:
print(line)
在這里,表達式 lines = (line.strip() for line in f)
執(zhí)行數(shù)據(jù)轉換操作。這種方式非常高效,因為它不需要預先讀取所有數(shù)據(jù)放到一個臨時的列表中去。它僅僅只是創(chuàng)建一個生成器,并且每次返回行之前會先執(zhí)行strip操作。
對于更高階的strip,你可能需要使用 translate()
方法。請參閱下一節(jié)了解更多關于字符串清理的內(nèi)容。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: