. Advertisement .
..3..
. Advertisement .
..4..
Computers are mostly used to store information and extract information from it. Python is one of the most powerful programming languages. We can use Python to get computers to do most routine processes. This blog is all about how we can find Character in a String in Python.
How Can You find Character in a String in Python?
To find a character in a string in Python, simply utilize find() or index(),… We can now get the character’s first place. Let’s consider the solutions of this:
1) Utilize index()
To find the first place of a character in a string in Python, simply utilize index().
Syntax:list_name.index(element, start, end)
# start (Optional)
# end (Optional)
Let’s consider the example of this:
myStr = 'My website is ITtutoria.net'
findChar = 'w'
print(myStr.index(findChar))
Result:
3
2) Utilize rfind()
To find the final place of a character in a string in Python, simply utilize rfind().
Syntax:string.rfind(value, start, end)
# start (Optional)
# end (Optional)
Let’s consider the example of this:
myStr = 'My website is ITtutoria.net'
findChar = 'e'
print(myStr.rfind(findChar))
Result:
25
3) Utilize find()
To find the first place of a character in a string in Python, simply utilize find().
Syntax:string.find(value, start, end)
# start (Optional)
# end (Optional)
Let’s consider the example of this:
myStr = 'My website is ITtutoria.net'
findChar = 'y'
print(myStr.find(findChar))
Result:
1
4) Utilize for loop
You can locate any position of the character by utilizing the for loop. Thus, it is extremely handy and simple to use. So, let’s have a look at an example.
myStr = 'My website is ITtutoria.net'
findChar = 'e'
list = []
for pos,char in enumerate(myStr):
if(char == findChar):
list.append(pos)
print(list)
Result:
[4, 9, 25]
Conclusion
Finding Character in a String in Python is a confusing problem. We hope this blog has helped clear the air around how to do it. If you have more questions about this topic, please comment below. Thank you for reading; we are always excited when one of our posts can provide useful information on a topic like this!
Leave a comment