user12181087
user12181087

Reputation:

How to fix this code so that it prints a string of letters with one of the positions replaced by a corresponding inputted number?

Question:

Create a function replaceCharAtPos(orig,pos) that 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.

Example of what should be inputted and outputted:

print (replaceCharAtPos("abcd",2))

This gives the output ab2d, because the number 2 corresponds the index position 2 of the string (index starts at 0) so it replaces "c" of "abcd"

Problem with my code:

def replaceCharAtPos(orig,pos):
    if pos >= (len(orig)):
        return orig
    orig = list(orig)
    orig[pos] = str(pos)
    return ''.join(orig)

When putting a two digit number, such as 12, the new string should take the second/LAST digit of 12 which is 2. Look below to see my problem with my code:

print (replaceCharAtPos('abcdefghijklmn',12))

The output I get is abcdefghijkl12n, but it is supposed to be abcdefghijkl2n. How to fix this? I've tried changing str(pos) to str(pos[-1]) but it doesn't work.

Thanks

Upvotes: 0

Views: 114

Answers (1)

Darren Christopher
Darren Christopher

Reputation: 4779

You can just use [-1] index in the converted index from the argument to ensure it always take the last digit if more than 1 digit supplied. You almost got it correct, but the way you did str(pos[-1]) is you tried to slice the pos which is an integer as opposed to the converted str.

In [10]: def replace_char_at_idx(orig, idx): 
    ...:     if idx >= (len(orig)): 
    ...:         return orig 
    ...:     orig = list(orig) 
    ...:     # Take always the last digit from the CONVERTED 
    ...:     orig[idx] = str(idx)[-1] 
    ...:     return ''.join(orig) 


In [11]: replace_char_at_idx("abcdefghijklmn", 12)                                                                                                                                                                
Out[11]: 'abcdefghijkl2n'

Upvotes: 1

Related Questions