Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเช็คว่า String จบด้วย Suffix ใดใน List ใน Python

ใช้ endswith(tuple) รับ tuple ของ suffixes

ตัวอย่าง

string = 'core java'
print(string.endswith(('txt', 'xml', 'java', 'orld')))

ผลลัพธ์

True

วิธี Regex: ใช้ $ (end of line) และ grouping () คั่นด้วย |

>> import re
>>> string = 'core java'
>>> bool(re.search('(java|xml|py|orld)$', string))
True
>>> bool(re.search('(java|xml|py|orld)$', 'core java'))
True
>>> bool(re.search('(java|xml|py)$', 'Hello world'))
False