Python:查找字符在字符串中的位置

时间:2023-01-03 21:12:25

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