When you come across the string question the interviewer may always
increases the level 1 by 1 to test your knowledge.
Replace first occurrence of letter with another is one of the favorite question in interview room.
Let try to break it
- find is a method which will give us the first occurrence of letter index
- As string is not mutable [ cannot make any changes] , we may need to convert it to list
- After converting to list , can easily perform assignment & reconvert back to string via join
# Replace 'i' with 'k'
strname='python is simple'
replaceLetter = 'i'
replaceLetterIndx=strname.find(replaceLetter)
lst = list(strname)
lst[replaceLetterIndx] = 'k'
print(''.join(lst))
Note : You cannot make use of replace method as it is going to replace all letters wherever it is coming in a string.
0 Comments