PYTHON QUESTIONS Write a function that finds and returns the

PYTHON QUESTIONS

Write a function that finds and returns the index of the first occurrence of a given character within a given string. For example, the index of the letter \'q\' in the string \'the quick brown fox is quiet\', is 4. Write a program that inputs a string and calls a function to return a different string in which all successive occurrences of its first letter are changed to \'%\'. Print the returned string. Do this until the user wishes to stop. For example: \'aardvark\' will be \'a%rdv%rk\'.

Solution

def get_index(c,data):
   for i in range(len(data)):
       # finding the character.
       if(data[i] == c):
           return i;
   return -1;
print(get_index(\'q\',\'the quick brown fox is quiet\'))

def replace_first_char(str):
   # create a new string.
   new_str = \"\"+str[0]
   for i in range(1,len(str)):
       # add \'%\' or str char based on condition check.
       if(str[i] == str[0]):
           new_str += \'%\'
       else:
           new_str += str[i]
   return new_str
  
print \"Enter s exiting.\"
while(True):
   str = raw_input(\"Enter String:\")
   if(str==\"s\"):
       break
   print replace_first_char(str)
          
#sample output
#4
#Enter s exiting.
#Enter String: aardvak
#a%rdv%k
#Enter String: hellooh
#helloo%
#Enter String: s

PYTHON QUESTIONS Write a function that finds and returns the index of the first occurrence of a given character within a given string. For example, the index of

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site