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

Kiểm tra chuỗi bắt đầu bằng XYZ trong Python

Python có method startswith(string) trong class String. Method nhận prefix string muốn tìm và gọi trên string object. Gọi như sau:

>>> 'hello world'.startswith('hell')
True
>>> 'hello world'.startswith('nope')
False

Cách khác: dùng re.search('^' + prefix, string) từ module re (regular expression). Regex hiểu ^ là start of line, nên tìm prefix làm sau:

>>> import re
>>> bool(re.search('^hell', 'hello world'))
True
>>> bool(re.search('^nope', 'hello world'))
False