Geeker_odd 发表于 2021-7-23 20:34:14

如何让find或index把字符串位置都标出来?


在学习字符串的操作方法时,碰到个问题:

如何让find(或index)把符合的字符串位置都找出来?按目前的方法只找出第一个位置

>>> str = '不管在哪里不论哪里困难何人在哪里干扰哪里出问题'
>>> str.find('哪里',0,len(str))
3

qiuyouzhi 发表于 2021-7-23 20:42:47

用正则表达式,或者 find 一次就 replace 一次

3236654291 发表于 2021-7-23 23:03:43

建议不要使用内置函数做变量名

3236654291 发表于 2021-7-23 23:40:09

本帖最后由 3236654291 于 2021-7-23 23:49 编辑

s= '不管在哪里不论哪里困难何人在哪里干扰哪里出问题'
#要求用户输入搜索的字符
content = input(':')
#把要求搜索的字符替换成一个空格
s = s.replace(content,' ')
a = []
for i in s:
    a.append(i)

num = 0

for i in a:
    if i == ' ':
      print(a.index(i) + num)
      a.remove(i)
      num += len(content)#取决于搜索对象的长度

      

3236654291 发表于 2021-7-23 23:43:23

这里用到了replace不知道行不行

Geeker_odd 发表于 2021-7-24 12:17:29

qiuyouzhi 发表于 2021-7-23 20:42
用正则表达式,或者 find 一次就 replace 一次

您好!正则表达式我不会,在《零基础入门学习python》书里面有吗?

qiuyouzhi 发表于 2021-7-24 12:28:35

Geeker_odd 发表于 2021-7-24 12:17
您好!正则表达式我不会,在《零基础入门学习python》书里面有吗?

有的

Geeker_odd 发表于 2021-7-24 13:36:56

3236654291 发表于 2021-7-23 23:40


你这个代码可以,谢谢!

但是,我按我的思路,使用replace写了一段代码,却不行。不知道问题出在哪里?麻烦帮我看一下:

str_test = '不管在哪里不论哪里有困难何人在哪里干扰哪里出问题'
appear = []
while '哪里'in str_test:
    position = int(str_test.find('哪里'))
    appear.append(position)
    str_test.replace('哪里','where')

print(appear)

print(str_test)

运行后是空的,啥也没有:

================================================================================ RESTART: D:/Practice/find_replace for string.py ================================================================================

3236654291 发表于 2021-7-24 13:40:32

Geeker_odd 发表于 2021-7-24 13:36
你这个代码可以,谢谢!

但是,我按我的思路,使用replace写了一段代码,却不行。不知道问题出在哪里 ...

我看看

3236654291 发表于 2021-7-24 13:48:10

str_test = '不管在哪里不论哪里有困难何人在哪里干扰哪里出问题'
appear = []
while '哪里' in str_test:
    position = int(str_test.find('哪里'))
    appear.append(position)
    str_test = str_test.replace('哪里','where')#你没有重新赋值给str_test
    #其次,replace这个函数是把所有的'哪里'一次性替换成where
    #再其次,被替换的字符串长度要与'哪里'字符串长度相同

print(appear)

print(str_test)


所以实际上你这个代码是行不通的

Geeker_odd 发表于 2021-7-24 13:50:31

好的,非常感谢!!!

Geeker_odd 发表于 2021-7-24 14:16:45

3236654291 发表于 2021-7-24 13:48
所以实际上你这个代码是行不通的

我改进了一下,换这样就可以了:

str_test = '不管在哪里不论哪里有困难何人在哪里干扰哪里出问题'
appear = []
while '哪里'in str_test:
    position = int(str_test.find('哪里'))
    appear.append(position)
    str_test = str_test.replace('哪里','替换',1)

print(appear)

print(str_test)

3236654291 发表于 2021-7-24 14:26:09

Geeker_odd 发表于 2021-7-24 14:16
我改进了一下,换这样就可以了:

str_test = '不管在哪里不论哪里有困难何人在哪里干扰哪里出问题'


{:10_298:}
页: [1]
查看完整版本: 如何让find或index把字符串位置都标出来?