python 判断字符串是否包含指定字符
时间: 2023-09-05 16:08:35 浏览: 56
可以使用 in 关键字来判断字符串中是否包含指定字符,例如:
```python
my_str = "Hello World"
if "World" in my_str:
print("Yes")
else:
print("No")
```
运行结果为:Yes
另外也可以使用 find 方法来查找指定字符在字符串中的位置,如果返回的结果为 -1,则表示字符串中不包含指定字符,例如:
```python
my_str = "Hello World"
if my_str.find("World") != -1:
print("Yes")
else:
print("No")
```
同样的运行结果为:Yes
相关问题
python 判断字符串是否包含指定字符串
以下是两种判断字符串是否包含指定字符串的方法:
1. 使用in运算符(推荐使用)
```python
def demo():
str1 = "b"
str2 = "abc"
if str1 in str2:
print("存在")
else:
print("不存在")
demo()
```
输出结果为:存在
2. 使用find方法
```python
def demo():
str1 = "a"
str2 = "abc"
if str2.find(str1) >= 0:
# 包含的话,返回第一次出现的位置,位置下标是从0开始,没有的话为负数
print("包含")
else:
print("不包含")
demo()
```
输出结果为:包含
python 2.7 判断 字符串是否包含指定字符 脚本
可以使用 Python 2.7 内置的字符串方法来判断一个字符串是否包含指定字符。可以使用 `in` 关键字来实现:
```
string = "hello world"
if "world" in string:
print("包含指定字符")
else:
print("不包含指定字符")
```
在上面的代码中,我们首先定义了一个字符串 `string`,然后使用 `in` 关键字来判断字符串中是否包含指定字符 `"world"`。如果包含,则输出 `"包含指定字符"`,否则输出 `"不包含指定字符"`。