如何在Python中去除字串中的所有標點符號?
去除Python字串中所有標點符號可以使用多種方法。以下是一些示例
使用string.punctuation
示例
string.punctuation常量包含所有ASCII標點符號。我們可以使用此常量來去除字串中的所有標點符號。
我們使用列表推導式迭代字串中的每個字元,並檢查它是否不在string.punctuation常量中。如果它不是標點符號,我們將其新增到no_punct變數中。
import string # sample string with punctuation text = "Lorem, Ipsum!!!" # remove punctuation no_punct = "".join(char for char in text if char not in string.punctuation) print(no_punct)
輸出
Lorem Ipsum
使用正則表示式
我們也可以使用正則表示式來去除字串中的所有標點符號。
示例
我們使用re.sub()方法將所有非單詞字元和非空格字元替換為空字串。
import re # sample string with punctuation text = "Lorem, Dolor!!!" # remove punctuation using regular expression no_punct = re.sub(r'[^\w\s]', '', text) print(no_punct)
輸出
Lorem Dolor
使用translate()
translate()方法也可以用於去除字串中的標點符號。
示例
我們使用str.maketrans()方法建立一個轉換表,並將其傳遞給translate()方法以去除字串中表中的所有字元。
import string
# sample string with punctuation
text = "Lorem, Ipsum!!!"
# create a translation table
table = str.maketrans('', '', string.punctuation)
# remove punctuation
no_punct = text.translate(table)
print(no_punct)
輸出
Lorem Ipsum
以下是如何在Python中去除字串中所有標點符號的更多示例
使用迴圈迭代字元
我們還可以迴圈遍歷字串中的每個字元並去除任何標點符號。
示例
我們迴圈遍歷字串中的每個字元,並檢查它是否是字母數字字元(字母或數字)或空格字元。如果是,我們將其新增到no_punct變數中。這樣,我們就可以從結果字串中排除任何標點符號。
# sample string with punctuation
text = "Foo, Bar!!!"
# remove punctuation using a loop
no_punct = ""
for char in text:
if char.isalnum() or char.isspace():
no_punct += char
print(no_punct)
輸出
Foo Bar
使用replace()方法
我們還可以使用replace()方法去除字串中的所有標點符號。
示例
我們使用replace()方法將每個標點符號(句點、逗號、感嘆號和問號)替換為空字串。這樣,我們就可以去除字串中的所有標點符號。
# sample string with punctuation
text = "Fubar, Quz!!!"
# remove punctuation using the replace() method
no_punct = text.replace(".", "").replace(",", "").replace("!", "").replace("?", "")
print(no_punct)
輸出
Fubar Quz
使用re模組和標點符號列表
我們還可以使用re模組和標點符號列表來去除字串中的所有標點符號。
示例
我們使用re.sub()方法替換所有不是字母、數字或空格的字元為空字串。正則表示式[^a−zA−Z0−9\s]+匹配任何不是字母、數字或空格的字元。
import re
# sample string with punctuation
text = "Foobar, Baz?"
# remove punctuation using the re module and a list of punctuation characters
no_punct = re.sub('[^a-zA-Z0-9\s]+', '', text)
print(no_punct)
輸出
Foobar Baz
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP