Fork me on GitHub

Python 查找字符在字符串中出现的位置

如下所示:

str_1='wo shi yi zhi da da niu '
char_1='i'
nPos=str_1.index(char_1)
print(nPos)

运行结果:7

========是使用find==========

str_1='wo shi yi zhi da da niu '
char_1='i'
nPos=str_1.find(char_1)
print(nPos)

结果:5

========如何查找所有‘i'在字符串中位置呢?===========

#开挂模式
str_1='wo shi yi zhi da da niu '
char_1=str(input('Please input the Char you want:'))
count=0
str_list=list(str_1)
for each_char in str_list:
 count+=1
 if each_char==char_1:
  print(each_char,count-1)

运行结果:

Please input the Char you want:i
i 0
i 1
i 2
i 3
posted @ 2021-04-02 14:38  君乐豹  阅读(3512)  评论(0编辑  收藏  举报
Live2D