Python Find Position of Specific Character in String
In Python, we can usefind()method to find the position of a specific character in a string.find()The method returns the index position of the first occurrence of the character in the string; if the character does not exist, it returns -1.
Example
# Define a string
text = "Hello, welcome to the world of Python."
# Find the position of character 'w'
position = text.find('w')
# Output result
print("The position of 'w' is:", position)
text = "Hello, welcome to the world of Python."
# Find the position of character 'w'
position = text.find('w')
# Output result
print("The position of 'w' is:", position)
Code explanation:
text = "Hello, welcome to the world of Python.": Define a stringtext。position = text.find('w'): Usefind()method to find character'w'in the stringtextand store the result in variableposition.print("The position of 'w' is:", position): Output character'w'position.
Output result:
The position of 'w' is: 7
In this example, the character'w'has index position 7 in the string.
Python3 Examples