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

Xóa ký tự đặc biệt, dấu câu, space khỏi string Python

Để xóa ký tự đặc biệt, dấu câu, space khỏi string, iterate string và filter non-alphanumeric. Ví dụ:

>>> string = "Hello $#! People   Whitespace 7331"
>>> ''.join(e for e in string if e.isalnum())
'HelloPeopleWhitespace7331'

Regular expression cũng xóa non-alphanumeric. re.sub(regex, string_to_replace_with, original_string) substitute non-alphanumeric bằng empty string. Ví dụ:

>>> import re
>>> re.sub('[^A-Za-z0-9]+', '', "Hello $#! People   Whitespace 7331")
'HelloPeopleWhitespace7331'