# Solution Exercise 97 *: python algorithm which determines the index of a character in a string

#### Exercise 97 *

Write a python algorithm as a function which takes as parameter a couple (s, x) formed by a text string s and a char x and which returns the index of the second position of the character x in the string s without using no predefined function. The function should return -1 if the char x is not in the string s. Example if s = ‘python programming language’ and x = ‘p’, the function returns the index: 7

#### Solution

``# function that determines the postions list of char x in within the string s def listPositions (s, x):    # initialize the list of positions of the character x in the string s    listPos = []    # browse the characters of the string s    for i in range (0, len (s)):        if s [i] == x:            listPos.append (i)    if len (listPos) >= 2:        return listPos     else:        return -1# Examples, x = 'python programming language', 'p'print ("The character position of", x, "in s is:", listPositions (s, x))# The output is:# The character position of p in s is: 7``
Younes Derfoufi
my-courses.net