Python | Find the position of a character in a given string



Let`s discuss a few methods to solve the problem.

Method # 1: Using the naive method

# Python3 demo code
# find the first character position
# on this line

 
# Initializing string

ini_string = ` abcdef`

 
# Character to search

c = "b"

# print start line and character

print ( "initial_st ring: " , ini_string, " character_to_find: " , c)

 
# Using the naive method

res = None

for i in range ( 0 , len (ini_string)):

if ini_string [i] = = c:

res = i + 1

break

  

if res = = None :

print ( " No such charater available in string " )

else :

print ( " Character {} is present at {} " . format (c, str (res)))

Exit :

 initial_string: abcdef character_to_find: b Character b is present at 2 

Method # 2: Using find

This method returns -1 if there is no character.

# Python3 code for demonstrations
# find the first character position
# on this line

 
# Initializing string

ini_string = `abcdef`

ini_string2 = `xyze`

  
# Character to search

c = " b "

# print start line and character

print ( "initial_strings:" , ini_string, ""

ini_string2, "character_to_find:" , c)

 
# Using the find method

res1 = ini_string.find (c)

res2 = ini_string2.find (c)

 

if res1 = = - 1 :

print ( "No such charater available in string {}" . format (

  ini_string))

else :

print ( "Character {} in string {} is present at {}" . format (

c, ini_string, str (res1 + 1 )))

 

if res2 = = - 1 :

print ( " No such charater available in string {} " . format (

ini_string2))

else :

print ( "Character {} in string {} is present at {}" . form at (

c, ini_string2, str (res2 + 1 )))

Output:

 initial_strings: abcdef xyze character_to_find: b Character b in string abcdef is present at 2 No such charater available in string xyze 

Method # 3: Using index ()

This method raises a ValueError if a character is missing

# Python3 demo code
# find the first character position
# on this line

 
# Initializing with string

ini_string1 = `xyze`

 
# Character to search

c = "b"

# print start line and character

print ( "initial_strings:" , ini_string1,

"character_to_find:" , c)

  
# Using the index method

try :

res = ini _string1.index (c)

print ( "Character {} in string {} is present at {}" . format (

  c , ini_string1, str (res + 1 )))

except ValueError as e:

  print ( " No such charater available in string {} " . format (ini_string1))

Output:

 initial_strings : xyze character_to_find: b No such charater available in string xyze