在给定字符串中查找某指定的字符python
时间: 2023-05-23 09:04:21 浏览: 360
A:
可以使用字符串的find()方法来查找某个指定字符在字符串中第一次出现的位置。示例如下:
```python
# 定义给定字符串
given_str = "This is a sample string."
# 查找字符 "s"
index = given_str.find("s")
if index != -1:
print(f"The character 's' is found at index {index} in the given string.")
else:
print(f"The character 's' is not found in the given string.")
```
输出结果:
```
The character 's' is found at index 3 in the given string.
```
另外,如果只是判断某个字符是否在给定字符串中出现过,可以直接使用in关键字来判断,示例如下:
```python
# 定义给定字符串
given_str = "This is a sample string."
# 判断字符 "s" 是否在字符串中
if "s" in given_str:
print("The character 's' is found in the given string.")
else:
print("The character 's' is not found in the given string.")
```
输出结果:
```
The character 's' is found in the given string.
```
阅读全文