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

วิธีลบเครื่องหมายวรรคตอนออกจากสตริงใน Python

วิธีเร็วที่สุดลบ punctuation ทั้งหมดจากสตริง คือใช้ str.translate()

ตัวอย่าง

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

ผลลัพธ์

string With Punctuation

ตัวอย่าง

ถ้าต้องการวิธีอ่านง่ายกว่า วนลูปเซตและข้าม punctuation

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