日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python去除空格,tab制表符和\n換行符的小技巧分享_python

作者:AshleyXM ? 更新時間: 2023-03-27 編程語言

python去除空格,tab制表符和\n換行符

python中常用的替換字符串的函數有replace(),其用法相信大家都比較熟悉

舉個例子

str="hello world ?hi there"
str.replace(" ","") ?#將str中的空格用空串替代,str本身不變,只改變顯示的結果

然而,當處理大量文本的時候,需要把文本中所有的空格、制表符和換行符全部都換為空串時,replace()函數不是一個好的選擇。

原因是首先寫法太復雜,其次是它的替代效果太局限,我之所以這么說是因為今天在做項目的時候遇到的一個給定的文本中出現的空格很怪異,它既不是普通的單個空格,也不是制表符,更不是換行符,最后用replace()來做怎么都替換不了那個“怪異”的空格。

這里推薦使用re模塊中的sub()函數來去除字符串中的所有空格,制表符和換行符,用法如下:

import re
str="""
hello ?123?? ??? ?world ?456

hello ?wish you good luck!
"""
print(re.sub('\s|\t|\n','',str)) ?#\s代表空格,\t代表制表符,\n代表換行符

這種寫法和replace()比起來更簡單,而且re.sub()的使用也很靈活,所以建議使用re.sub()來實現去除空格的任務。

上面的代碼我發現還可以更加簡化:

print(re.sub('\s','',str))

即re.sub()函數的pattern參數中不包含\t和\n也可以實現替換它們的功能,我想應該是\s包含了\t和\n,這也是為什么我所遇到的“怪異”的空格re.sub()能去掉的原因了吧。但是\t不包含\s和\n的功能,\n也不包含\s和\t的功能,不要誤用哦!

python內容去掉“空格,制表符,其他空白”

學習python爬蟲的時候,部分內容無法用xpath匹配,就考慮用正則表達式,此時先把response返回來的list通過jion來轉換成string

		body1=response.xpath('//body//text()').extract()
        body1=''.join(body1)
        body1 = re.sub('\n', '', body1).replace(' ', '').strip()
        body1=re.sub('\s','',body1)

在pycharm中運行發現獲取的內容是空白。

嘗試打印長度,發現不為0,所以就需要想辦法把換行符去掉,把空格去掉。

re.sub('\n', '', body1)

利用re模塊的sub()替換掉換行,sub(pattern, repl, string, count=0, flags=0)

其中pattern是正則表達式,模式字符串。

  • repl是要替換成的內容
  • string是要進行編輯的string內容

這三個參數為必選,還有下面兩個默認參數。

  • count=0:模式匹配后替換的最大次數,默認 0 表示替換所有的匹配。
  • flags=0標志位,用于控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等

  • \n:會被處理為對應的換行符;
  • \r:會被處理為回車符;

常用的去掉空格的方法

去掉左邊空格

str1 = " String's type is str "
print(str1,end='')
print('end')
print(str1.lstrip(),end='')
print('end')
# String's type is str end
#String's type is str end

去掉右邊空格

str1 = " String's type is str "
print(str1,end='')
print('end')
print(str1.rstrip(),end='')
print('end')

# String's type is str end
# String's type is strend

去掉兩頭的空格

str1 = " String's type is str "
print(str1,end='')
print('end')
print(str1.strip(),end='')
print('end')

# String's type is str end
#String's type is strend

用字符串的方法去掉所有空格,制表符或者其他空白

str1 = " String's type is str "
print(str1,end='')
print('end')
print(str1.replace(' ', ''),end='')
print('end')
# String's type is str end
#String'stypeisstrend

用正則的方法去掉所有空格,制表符或者其他空白

import re
str1 = " String's type is     str "
print(str1,end='')
print('end')
str1=re.sub(r"\s+", "", str1)
print(str1.replace(' ', ''),end='')
print('end')

其中正則表達式\s+表示匹配空的內容1到無限次。

表示匹配前一個字符1到無限次

總結

原文鏈接:https://blog.csdn.net/AshleyXM/article/details/106246081

欄目分類
最近更新