Python_去除字符串中的空格

作者:Gakki

01. strip() 方法

  • strip() :用于移除字符串頭尾指定的字符(默認為空格)或字符序列。
    注: 該方法只能刪除開頭或結(jié)尾的字符,不能刪除中間部分的字符。
old_data = " a b c d 1 1 3 1 "
new_data = old_data.strip()
old_data2 = "com.123fa.comsfasf.comasdfrs324.com"
new_data2 = old_data2.strip(".com")
print(new_data)
print(new_data2)
  • 輸出結(jié)果:
a b c d 1 1 3 1
123fa.comsfasf.comasdfrs324

02. lstrip()方法

  • lstrip():用于截掉字符串左邊的空格或指定字符。
old_data = " a b c d 1 1 3 1 "
new_data = old_data.lstrip()
old_data2 = "com.123fasfasf asdfrs324.com"
new_data2 = old_data2.lstrip("com")
print(new_data)
print(new_data2)
  • 輸出結(jié)果:
a b c d 1 1 3 1 
.123fasfasf asdfrs324.com

03. rstrip()方法

  • rstrip():用于刪除 string 字符串末尾的指定字符,默認為空白符,包括空格、換行符、回車符、制表符。
old_data = " a b c d 1 1 3 1 "
new_data = old_data.rstrip()
old_data2 = "com.123fasfasf asdfrs324.com"
new_data2 = old_data2.rstrip("com")
print(new_data)
print(new_data2)
  • 輸出結(jié)果:
 a b c d 1 1 3 1
com.123fasfasf asdfrs324.

04. replace()方法

  • replace():把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數(shù)max,則替換不超過 max 次。
  • 語法:str.replace(old, new[, max])
old_data = " a b c d 1 1 3 1 "
new_data = old_data.replace(" ","")
old_data2 = "com.123fasfasf asdfrs324.com"
new_data2 = old_data2.replace("a", "A", 2)
print(new_data)
print(new_data2)
  • 輸出結(jié)果:
abcd1131
com.123fAsfAsf asdfrs324.com

05. join()方法 + split()方法

  • split():通過指定分隔符對字符串進行切片,如果第二個參數(shù) num 有指定值,則分割為 num+1 個子字符串。
  • 語法:str.split(str="", num=string.count(str))
  • join():用于將序列中的元素以指定的字符連接生成一個新的字符串。
old_data = " a b c d 1 1 3 1 "
# 1.將字符串按空格分割成列表
new_data = old_data.split()
print(new_data)
# 2.使用join()將列表內(nèi)容拼接成新的字符串
new_data = "".join(new_data)
print(new_data)
  • 輸出結(jié)果:
['a', 'b', 'c', 'd', '1', '1', '3', '1']
abcd1131

06. 使用正則表達式

import re
old_data = " a b c d 1 1 3 1 "
# 去掉空格
new_data = re.sub(r"\s+", "", old_data)
old_data2 = "com.123fa.com sfasf.com asdfrs324.com"
# 將 com 替換為 www
new_data2 = re.sub(r"com", "www", old_data2)
print(new_data)
print(new_data2)
  • 輸出結(jié)果:
abcd1131
www.123fa.www sfasf.www asdfrs324.www
  • sub函數(shù):將整個字符串用新的字符串替換掉。
  • \s:匹配各種不同的空白符,如:空格、制表符、回車等。等價于 [\t\n\r\f]。
不足之處,歡迎留言補充?。?!
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容