Skip to content

Python find character in the string | Example code

  • by

Use String find() method to Python find character in the string in Python. The method will return the index value if the character occurs in a string or a substring of string if starting index beg and ending index end are given.

str.find(sub,start,end)

An end parameter is an option− This is the ending index, by default, it’s equal to the length of the string.

Python find character in the string Example

Simple example code. Finds the first occurrence of the character “w” in the given string.

txt = "Hello, welcome to my world."

res = txt.find("w")

print(res)

Output:

Python find character in the string

Q: How to Find the position of a character in a given string?

Answer: You can get the position of the character using the python find() or index() method.

Using find()

myString = 'Position of a character'

res = myString.find('s')

print(res)

Output: 2

Using index()

myString = 'Position of a character'

res = myString.index('a')

print(res)

Output: 12

Do comment if you have any doubts and suggestions on this Python char topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *