Home  >  Article  >  Backend Development  >  Python finds the position of a character in a string instance

Python finds the position of a character in a string instance

不言
不言Original
2018-05-02 11:06:107330browse

The following is an example of how to find the position of a character in a string using Python. It has a good reference value and I hope it will be helpful to everyone. Let’s come and take a look

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

##Run result: 7

======== is to use find==========

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

Result: 5

========How to find all 'i' positions in a string? ===========

#开挂模式
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)

##Run result:

Please input the Char you want:i
i 0
i 1
i 2
i 3

Related recommendations:

python search example of a file with a specified extension in a directory

The above is the detailed content of Python finds the position of a character in a string instance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn