0 votes
1 view
in Python by (47.8k points)

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

1 Answer

0 votes
by (107k 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.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...