How to get character position(index) in a string python with example

This tutorial explains about character’s position of a given string in Python language. The string is a group of characters enclosed in double quotes. Characters in a string are located with starting index of 0.

For example, Starting character position is 0.

How to Get character position in a String in python?

  • use find() function

String find function checks the given substring position and returns the position if a matching substring is found. Returns -1 if no match is found.

Syntax:

str.find(substring[, start[, end]])¶

Arguments:

  • substring - substring to search in a given string and returns the first occurrence of a string.
  • start and end options are optional, index, For example, start=1 and end=4 take a character from starting position 1 and the end position is equal to 3.

Returns: find() function returns

  • index position if found
  • -1 returned if no matching character/substring in a given string,

This function is case-sensitive.

Here is an example

name="John"

print( name.find('o'))
print( name.find('J'))
print( name.find('j'))

Output:

1
0
-1
  • index() function The string contains an index() function that returns the position or index of a given character in a string.

Syntax:

string.index(charcter[, start[, end]])

Arguments:

  • character - character to search in a given string and returns the first occurrence of a string.
  • start and end options are optional, index, For example, start=1 and end=4 take a character from starting position 1 and the end position is equal to 3.

Returns: index() function returns

  • index position if found
  • throws ValueError if no matching character in a given string,

This function is case-sensitive.

Here is an example

name="John"

print( name.index('o'))
print( name.index('J'))
print( name.index('j'))
1
0
Traceback (most recent call last):
File "a:\work\python\string.py", line 5, in <module>
print( name.index('j'))
ValueError: substring not found
  • use for index with string enumerate function

This is the way of finding a position using brute force search.

  • String is iterated using enumerate function
  • used for loop with index syntax
  • check each character and return the index if a matching character is found.

Here is an example

name="John"

for index, character in enumerate(name):
if "J"==character: {
print(index)
}
0

Conclusion

Learned multiple ways to find the position of a character in a string

  • index() function
  • find() function
  • for loop with index syntax

The first approach is better, It checks for matching and nonmatching use cases and return the position of a number, and good in performance compared with other two approaches the disadvantages with the other are

  • find() method throws ValueError if no match is found.
  • For loop iterates all characters in a string in the worst case, so not advisable interms o performance.