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

So sánh 2 string bằng regex trong Python

So sánh string dùng regex:

Ví dụ

import re

s1 = 'Pink Forest'
s2 = 'Pink Forrest'

if bool(re.search(s1, s2)):
    print('Strings match')
else:
    print('Strings do not match')

Kết quả

Strings do not match

Lưu ý: re.search(pattern, string) tìm pattern trong string. Ví dụ trên tìm 'Pink Forest' trong 'Pink Forrest' → không khớp (thiếu 'e').

Cách so sánh đơn giản hơn: s1 == s2 hoặc s1 in s2 (substring).