说说 Python 中的 in 与 not in 操作符
发布日期:2021-06-29 21:01:56 浏览次数:2 分类:技术文章

本文共 577 字,大约阅读时间需要 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

转载地址:https://deniro.blog.csdn.net/article/details/101163292 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:说说 Python 中,如何使用列表为多个变量赋值
下一篇:说说 Python 中如何迭代列表元素的同时,获取其下标

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月03日 17时13分12秒