python判断一个字符串是否在列表里
时间: 2024-05-01 21:19:14 浏览: 15
可以使用 `in` 关键字来判断一个字符串是否在列表里,示例如下:
```python
my_list = ['apple', 'banana', 'orange', 'pear']
if 'apple' in my_list:
print('apple is in the list')
else:
print('apple is not in the list')
```
输出结果为:`apple is in the list`
如果要判断一个字符串是否不在列表里,可以使用 `not in` 关键字,示例如下:
```python
my_list = ['apple', 'banana', 'orange', 'pear']
if 'watermelon' not in my_list:
print('watermelon is not in the list')
else:
print('watermelon is in the list')
```
输出结果为:`watermelon is not in the list`
相关问题
python判断多个字符串是否在列表里
可以使用列表推导式和in关键字来判断多个字符串是否在列表中,示例代码如下:
```python
strings = ['apple', 'banana', 'orange']
check_list = ['apple', 'pear', 'grape']
result = [string for string in check_list if string in strings]
print(result) # 输出 ['apple']
```
在以上代码中,`strings` 列表是被检查的列表,`check_list` 是需要判断是否在 `strings` 中的字符串列表,使用列表推导式将符合条件的字符串添加到 `result` 列表中,最后输出 `result` 列表即可。
python 判断某个字符串是否在另一个字符串里面
可以使用 Python 的 `in` 关键字来判断一个字符串是否在另一个字符串中。例如:
```python
string1 = "hello world"
string2 = "world"
if string2 in string1:
print("String2 is in String1")
else:
print("String2 is not in String1")
```
输出结果为:
```
String2 is in String1
```
上面的代码中,我们先定义了两个字符串 `string1` 和 `string2`,然后使用 `in` 关键字来判断 `string2` 是否在 `string1` 中。如果在,就输出 `String2 is in String1`,否则输出 `String2 is not in String1`。