close

How to find character in a string in python

Hello guys. How are you all? In this tutorial we are going to learn about How to find character in a string in python. We can find the position of the each elements in string By using below methods. In python the first element of the string is contain zero position and next one is contain first position. Thus on the basis of that we can find the position of each character by different methods. So lets learn this without wasting your time.

How to find character in a string in python

By using given methods you can find first position of the character, last position of the character and by using loop you can find the all position of a character. Lets learn this all methods.

  1. find character in a string in python

    to find character in a string in python just Use find(). fine() function is use for to find the position of the character in the string. By using str.find() you can find the character. By using it you can find the first position of the character. lets see this.
    str = 'hello world' substr = 'l' print(str.find(substr)) Output : 2

  2. How to find character in a string in python

    to find character in a string in python just Use rfind(). rfind() is quite similar to find() but the difference is find() give the first position of the character and rfind() will give the last position of the element. Lets see this by given below example: str = 'hello world' substr = 'l' print(str.rfind(substr)) Output : 9

Method 1: Use find()

fine() function is use for to find the position of the character in the string. By using str.find() you can find the character. By using it you can find the first position of the character. lets see this.

str = 'hello world'
substr = 'l'
print(str.find(substr))

Output :

2

Method 2: Use rfind()

rfind() is quite similar to find() but the difference is find() give the first position of the character and rfind() will give the last position of the element. Lets see this by given below example:

str = 'hello world'
substr = 'l'
print(str.rfind(substr))

Output :

9

Method 3: Use index()

index is similar to find(). It also gives the first position of thecharacter. Lets see this by given example:

str = 'hello world'
substr = 'l'
print(str.index(substr))

Output :

2

Method 4: Use for loop

By using for loop you can find the character in string. And most importantly you can find all the position of an element or character. So this is the most important method. Lets learn this guys by below example:

str = 'hello world'
substr = 'l'
lst = []
for pos,char in enumerate(str):
    if(char == substr):
        lst.append(pos)
print(lst)

Output :

[2, 3, 9]

Conlusion

Hope all 6 Method Are Useful For You. Comment Below Which Method You Used To Convert String To Datetime In Python. Thank You.

Also Read

Leave a Comment