说说 Python 中的 in 与 not in 操作符

719 阅读1分钟

1 列表

in 与 not in 操作符, 可以判定一个值是否在列表中。

books = ['梦的化石', '冬泳', '鱼翅与花椒']

new_book = '莫斯科绅士'
if '莫斯科绅士' not in books:
    print(new_book + '不在书单中,现在添加……')
    books.append(new_book)
if '莫斯科绅士' in books:
    print(new_book + '已经在书单中。')

print('books = ' + str(books))

运行结果:

莫斯科绅士不在书单中,现在添加…… 莫斯科绅士已经在书单中。 books = ['梦的化石', '冬泳', '鱼翅与花椒', '莫斯科绅士']

in 与 not in 操作符需要连接两个值,它们分别是:需要在列表中查找的值以及列表对象。

2 字符串

字符串也可以利用 in 与 not in 操作符来判断某个字符是否存在:

is_exist = '绅士' in '莫斯科绅士'
print(is_exist)

is_exist = '科' in '莫斯科绅士'
print(is_exist)

is_not_exist = '冬泳' not in '莫斯科绅士'
print(is_not_exist)

运行结果:

True True True