Python finding the position of a specific character in a string
In Python, we can use find() method to find the position of a specific character in a string.find() method returns the index of the first occurrence of the character in the string, or -1 if the character does not exist.
Example
Define a string
text
=
"Hello, welcome to the world of Python."
Find the position of the character 'w'
position
=
text.
find
(
'w'
)
Output result
(
"The position of 'w' is:"
,
position
)
Code analysis:
text = "Hello, welcome to the world of Python.": define a stringtext。position = text.find('w'): When usingfind()method finds the character'w'in the stringtextand stores the result in the variablepositionit.print("The position of 'w' is:", position): output the character'w''s position.
Output result:
The position of 'w' is: 7
In this example, the character 'w' has an index position of 7 in the string.
Python3 Examples