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

Python finds the position of a character in a string instance

不言
Release: 2018-05-02 11:06:10
Original
7415 people have browsed it

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)
Copy after login

##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)
Copy after login

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)
Copy after login

##Run result:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template