找出字符串中第一个出现“学生”的字符索引号
时间: 2023-05-11 10:02:32 浏览: 97
可以使用 Python 的 find() 方法来找出字符串中第一个出现“学生”的字符索引号,示例代码如下:
```python
s = "这是一个学生,那也是一个学生"
index = s.find("学生")
print(index) # 输出 5
```
在这个例子中,字符串 s 中第一个出现“学生”的字符索引号是 5。
相关问题
python里在字符串中找出第一个只出现一次的字符
可以使用 collections.Counter 和字符串的 find 方法来实现。代码如下:
```python
import collections
def first_unique_char(s: str) -> int:
freq = collections.Counter(s)
for i, c in enumerate(s):
if freq[c] == 1:
return i
return -1
```
函数 first_unique_char 接收一个字符串 s 作为参数,返回该字符串中第一个只出现一次的字符的索引。如果不存在这样的字符,则返回 -1。
具体实现时,首先使用 Counter 函数统计字符串中每个字符出现的次数,然后遍历字符串,找到第一个出现次数为 1 的字符即可。
输入一个字符串,再输入两个字符,求这两个字符在字符串中的索引
好的,我理解了。对于您的问题,可以使用 Python 中的 find() 方法来找出两个字符在字符串中的索引位置。下面是一个示例代码:
```python
s = input("请输入一个字符串:")
c1 = input("请输入要查找的第一个字符:")
c2 = input("请输入要查找的第二个字符:")
i1 = s.find(c1)
i2 = s.find(c2)
print("{0} 在字符串中的索引为 {1}".format(c1, i1))
print("{0} 在字符串中的索引为 {1}".format(c2, i2))
```
您可以尝试输入不同的字符串和字符来测试代码的效果。如果您有其他问题,请随时提出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)