python查找所有指定字符
时间: 2023-11-28 14:03:48 浏览: 72
可以使用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的os和re模块来实现字符串查找,具体代码如下:
```python
import os
import re
def find_files(root, pattern):
for dirpath, dirs, files in os.walk(root):
for file in files:
if file.endswith('.txt'): # 只查找txt文件
filepath = os.path.join(dirpath, file)
with open(filepath, 'r') as f:
content = f.read()
if re.search(pattern, content):
print(filepath)
find_files('/path/to/root', 'hello world')
```
以上代码会在指定路径下查找所有的txt文件,并在文件中查找包含"hello world"子串的文件,找到后输出文件路径。你可以根据自己的需要修改文件类型和查找的字符串。
python 查找包含指定字符的文件夹
您可以使用Python中os模块的walk()函数遍历目录,并使用in关键字检查每个目录名是否包含指定字符。以下是示例代码:
``` python
import os
def find_folders_with_char(root_dir, char):
folders = []
for dirpath, dirnames, filenames in os.walk(root_dir):
if char in dirpath:
folders.append(dirpath)
return folders
# 调用函数并打印结果
root_dir = "/path/to/search"
char = "example"
folders = find_folders_with_char(root_dir, char)
print(folders)
```
这段代码将在root_dir中搜索所有包含"example"的文件夹,并返回一个包含这些文件夹路径的列表。
阅读全文
相关推荐















