python查找所有指定字符
时间: 2023-11-28 13:03:48 浏览: 76
可以使用Python的字符串方法`find()`或`index()`来查找指定字符在字符串中的位置。这两个方法的区别在于,如果指定字符不存在于字符串中,`find()`方法返回-1,而`index()`方法会抛出一个异常。
如果要查找字符串中所有指定字符的位置,可以使用一个循环来遍历字符串,并将每个字符的位置保存在一个列表中。
下面是一个示例代码:
```python
s = "hello world"
char = 'l'
positions = []
for i in range(len(s)):
if s[i] == char:
positions.append(i)
print(positions)
```
输出结果为:`[2, 3, 9]`,表示字符'l'在字符串中的位置分别是2、3和9。
相关问题
python查找指定字符
可以使用Python中的字符串方法`find()`或`index()`来查找指定字符在字符串中的位置。
`find()`方法会从左往右查找指定字符,并返回它在字符串中的第一个出现位置的索引值。如果指定字符不存在,则返回-1。
例如,查找字符串s中字符'a'的位置:
```python
s = 'hello world'
pos = s.find('a')
print(pos) # 输出: -1
```
`index()`方法与`find()`类似,但是如果指定字符不存在,则会抛出ValueError异常。
例如,查找字符串s中字符'o'的位置:
```python
s = 'hello world'
pos = s.index('o')
print(pos) # 输出: 4
```
如果要查找字符串中所有指定字符的位置,则可以使用列表推导式:
```python
s = 'hello world'
char = 'l'
pos = [i for i, c in enumerate(s) if c == char]
print(pos) # 输出: [2, 3, 9]
```
以上代码使用了字符串方法`enumerate()`,它返回一个枚举对象,包含字符串中字符的索引和字符本身。列表推导式遍历枚举对象,并将所有字符为指定字符的索引保存到列表中。
python查找指定字符头哥
在Python中,如果你想要查找一个字符串中是否包含特定的字符或者子串,你可以使用`in`关键字或者`find()`、`index()`函数。以下是几种方法:
1. **使用`in`关键字**:
```python
string = "头哥"
if '哥' in string:
print("找到'哥'")
```
2. **使用`find()`函数**:
```
string = "头哥"
position = string.find('哥')
if position != -1:
print(f"'哥'的位置是 {position}")
else:
print("'哥'不在字符串中")
```
`find()`会返回子串第一次出现的位置,如果找不到则返回-1。
3. **使用`index()`函数**:
```python
string = "头哥"
try:
index = string.index('哥')
print(f"'哥'的位置是 {index}")
except ValueError:
print("'哥'不在字符串中")
```
`index()`也用于查找子串,但如果子串不存在,会抛出异常。
阅读全文
相关推荐















