|
发表于 2025-3-8 16:23:49
|
显示全部楼层
本帖最后由 jackz007 于 2025-3-8 18:33 编辑
使用 find() 的版本
- text = input(" What text : ")
- words = input("What words : ")
- e = []
- for w in words . split(' ') :
- k = text . find(w , 0)
- while k != -1 :
- e . append([k , k + len(w) - 1])
- k = text . find(w , k + 1)
- if e:
- e . sort()
- print(e)
复制代码
不使用 find() 的版本:
- text = input(" What text : ")
- words = input("What words : ")
- e = []
- for w in words . split(' ') :
- for k in range(len(text) - len(w) + 1) :
- if text[k : k + len(w)] == w :
- e . append([k , k + len(w) - 1])
- if e:
- e . sort()
- print(e)
复制代码
运行实况;
- D:\[00.Exercise]\[Python]>python x.py
- What text : I love FishC and FishC love me
- What words : FishC
- [[7, 11], [17, 21]]
- D:\[00.Exercise]\[Python]>python x.py
- What text : I love FishC and FishC love me
- What words : FishC love
- [[2, 5], [7, 11], [17, 21], [23, 26]]
- D:\[00.Exercise]\[Python]>python x.py
- What text : FCFCF
- What words : FCF FC
- [[0, 1], [0, 2], [2, 3], [2, 4]]
- D:\[00.Exercise]\[Python]>
复制代码 |
|