Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

How can I get the position of a character inside a string in python?

1 Answer

0 votes
by (106k points)

There are many ways to find the position of a character inside a string some of the important methods I am discussing here:-

So, if you want to find all the positions of a character in a string, you can use the enumerate()function for that below is the code that explains how to do that:

s = 'shak#spea#e' 

c = '#' 

print([pos for pos, char in enumerate(s) if char == c])

image

Another method you can use, which is the find() function this function will be very helpful in case if your string does not contain that character in that case this function will return -1.

How we use find()function:-

>>> myString = 'Position of a character'

>>> myString.find('s')

>>> myString.find('x')

image

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.6k points)

Browse Categories

...