Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xóa list ký tự trong string Python

Class string có method replace thay substring trong string. Dùng method này replace ký tự muốn xóa bằng empty string. Ví dụ:

>>> "Hello people".replace("e", "")
"Hllo popl"

Muốn xóa nhiều ký tự trong 1 dòng, tốt hơn dùng regular expression. Tách nhiều ký tự bằng "|" và dùng re.sub(chars_to_replace, string_to_replace_with, str). Ví dụ:

>>> import re
>>> re.sub("e|l", "", "Hello people")
"Ho pop"

Nếu đã có list ký tự muốn xóa, dùng join() tạo regex. Ví dụ:

>>> import re
>>> char_list = ['a', 'e', 'i', 'o', 'u']
>>> re.sub("|".join(char_list), "", "Hello people")
"Hll ppl"

Lưu ý: cũng dùng [] tạo group ký tự replace trong regex.