我們可以使用 Python 的 in
運算符來檢查字串是否在列表中。還有一個 not in
運算符來檢查字串是否不在列表中。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
# 字串在列表中
if 'A' in l1:
print('A is present in the list')
# 字串不在列表中
if 'X' not in l1:
print('X is not present in the list')
輸出:
A is present in the list
X is not present in the list
推薦閱讀:Python f-strings 讓我們看另一個例子,我們將要求用戶輸入要在列表中檢查的字串。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = input('Please enter a character A-Z:\n')
if s in l1:
print(f'{s} is present in the list')
else:
print(f'{s} is not present in the list')
輸出:
Please enter a character A-Z:
A
A is present in the list
使用 count() 在列表中查找字串
我們還可以使用 count() 函數來獲取字串在列表中出現的次數。如果它的輸出是 0,則表示該字串不在列表中。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = 'A'
count = l1.count(s)
if count > 0:
print(f'{s} is present in the list for {count} times.')
查找列表中字串的所有索引
沒有內置函數可以獲取列表中字串的所有索引列表。以下是一個簡單的程序,用於獲取字串在列表中出現的所有索引列表。
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C']
s = 'A'
matched_indexes = []
i = 0
length = len(l1)
while i < length:
if s == l1[i]:
matched_indexes.append(i)
i += 1
print(f'{s} is present in {l1} at indexes {matched_indexes}')
輸出:A 在 ['A', 'B', 'C', 'D', 'A', 'A', 'C'] 中出現,索引為 [0, 4, 5]
你可以從我們的GitHub存儲庫中查看完整的Python腳本和更多Python示例。
Source:
https://www.digitalocean.com/community/tutorials/python-find-string-in-list