Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีตัด Punctuation ทั้งหมดออกจาก String ใน Python

วิธีเร็วที่สุด: str.translate()

import string
s = "string. With. Punctuation?"
print(s.translate(None, string.punctuation))

ผลลัพธ์

string With Punctuation

วิธีอ่านง่ายกว่า: list comprehension

import string
s = "string. With. Punctuation?"
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
print(s)

ผลลัพธ์

string With Punctuation

หมายเหตุ Python 3: ใช้ str.maketrans('', '', string.punctuation) แทน