In: Computer Science
Define a function replaceCharAtPos(orig,pos) which receives two input parameters, a string (orig) and a positive integer number (pos).
If the number is a position within the string, the function should
return a new string. The new string should be the original
string except that instead of the original character in that
position pos, it should have the position number itself (if the
position number has more than 1 digit, the character should be
replaced by the digit in the units part of the position number,
e.g. 2 if the position number is 12).
If the number pos is not a valid position within the original
string orig, the string returned should be exactly the same as the
original string.
For example
replaceCharAtPos('abcd',1) should return 'a1cd'
replaceCharAtPos('abcd',10) should return 'abcd'
replaceCharAtPos('abcdefghijklmn',12) should return
'abcdefghijkl2n'
As an example, the following code fragment:
print (replaceCharAtPos("abcd",2))
should produce the output:
ab2d
language: Python
SOURCE CODE IN PYTHON:
def replaceCharAtPos(orig,pos): #function to replace character
in pos position of orig with unit digit of pos
if pos>=0 and pos<len(orig): #checking if pos is within
limits of the string
orig=orig[:pos]+str(pos%10)+orig[pos+1:] #removing character at pos
and inserting pos%10
return orig #returning the string
#testing the function
print(replaceCharAtPos("abcd",1))
print(replaceCharAtPos("abcd",10))
print(replaceCharAtPos("abcdefghijklmn",12))
OUTPUT: