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

Xóa substring ở cuối string Python

Muốn xóa substring ở cuối string, trước hết check string có kết thúc bằng substring đó. Nếu có, slice string giữ phần không có substring. Ví dụ:

def rchop(string, ending):
    if string.endswith(ending):
        return string[:-len(ending)]
    return string

chopped_str = rchop('Hello world', 'orld')
print chopped_str

Output:

Hello w

Nếu speed không quan trọng, dùng regex. Ví dụ:

>>> import re
>>> re.sub('orld$', '', 'Hello world')
Hello w