给你一个字符串数组 words 和一个字符串 s,其中 words[i] 和 s 只包含小写英文字母。
请你返回 words 中是字符串 s 前缀的字符串数目。
一个字符串的前缀是出现在字符串开头的子字符串。子字符串是一个字符串中的连续一段字符序列。
依次遍历 words 中的字符串。
直接使用字符串的 startswith 方法即可判定当前字符串是否是 s 的前缀。
2.4.3.2 参考答案
defcount_prefixes(words, s):
res = 0# 符合要求字符串个数for word in words:
if s.startswith(word):
res += 1return res
print(count_prefixes(["a","b","c","ab","bc","abc"], "abc"))
2.4.3.3 最佳实践
# 代码案例:统计字符串前缀# 遍历 words,取出每个字符串,判定当前这个字符串是否是 s 的前缀即可 (s 是否是以这个字符串开题的)defcount_prefixes(words: list, s: str):
count = 0for word in words:
if s.startswith(word): # 使用 in 操作可以判断 word 是不是 s 的一部分# s 是以 word 开头
count += 1return count # 注意缩进print(count_prefixes(['a','b','c','ab','bc','abc'], 'abc'))
print(count_prefixes(['a','a'], 'aa'))
import os
input_path = input('请输入待搜索路径:')
pattern = input('请输入待搜索关键词:')
for dirpath, dirnames, filenames in os.walk(input_path):
for f in filenames:
if pattern in f:
print(f'{dirpath}/{f}')
2.5.2 最佳实践
# 文件搜索工具# 很多目录,很多文件,想找到某个文件,就不太容易# 文件搜索工具——如 everything# 实现文件查找工具# 输入要查找的路径,输入要搜索的文件名(一部分)# 自动地在指定的路径进行查找# import os# input_path = input('请输入要搜索的路径:')# pattern = input('请输入要搜索的关键词:')# 递归查找,遇到子目录,就进到目录里面进行查找# OS.walk(OS:操作系统),只需要使用简单的循环就可以完成递归遍历的过程,就不必手写递归代码了# for dirpath, dirnames, filenames in os.walk(input_path):# print('----------------------------')# print(f'dirpath = {dirpath}')# print('dirnames:')# for name in dirnames:# print(name)# print('filename:')# for name in filenames:# print(name)# dirpath: 遍历到当前位置,对应的路径是啥# dirnames: 当前目录下,都有哪些目录,是一个列表,可以包含多个目录名# filenames: 当前目录下,都有哪些文件名,是一个列表,可以包含多个文件名# os.walk: os.walk 每次调用都能自动的去针对子目录进行递归的操作,只需要使用上述循环就可以把所有的路径都获取出来# 正式实现一下这里的功能import os
input_path = input('请输入要搜索的路径:')
pattern = input('请输入要搜索的关键词:')
for dirpath, _, filenames in os.walk(input_path):
for f in filenames:
if pattern in f:
print(f'{dirpath}/{f}')
# 这里只是一个简单粗暴的遍历,比不了 everything,不算特别高效