How do you replace only 1 character in a string in python?

Question:

I am trying to write a function in python that takes a phone number as a string and provides me all the permutations of number combinations that are 1 "character" away.

So for example if the phone number is 9879876 it would return 8879876, 6879876, 9579876, 9779876, 9979876, so on so forth. I have tried mapping it out each of the 10 options using str.replace but it changes all instances of that number rather than only that specific number. I’ve also tried using the "count" parameter in the replace function but it still did not work.

So to clarify, I wanted to create permutations with a pattern format.

rep1 = ["2","4"]
rep2 = ["1","3","5"]
rep3 = ["2","6"]
rep4 = ["1","5","7"]
rep5 = ["2","4","6","8"]
rep6 = ["3","5","9"]
rep7 = ["4","8"]
rep8 = ["5","7","9","0"]
rep9 = ["6","8"]
rep0 = ["8"]

If the current digit in the loop is 1 then replace that with each char in rep1 while keeping the rest of the phone number intact. If the current digit is a 2 then replace it with each char in rep2. I’m didn’t use this list approach in my current code, its just for explanation of the conditional changes.

def myfunc(phone:str):
    for digit in phone:
        if digit == "1":
            newphone = phone.replace("1", "2", 1)
            print(newphone)
            newphone = phone.replace("1", "4",1)
            print(newphone)
        if digit == "2":
            newphone = phone.replace("2", "1",1)
            print(newphone)
            newphone = phone.replace("2", "3",1)
            print(newphone)
            newphone = phone.replace("2", "5",1)
            print(newphone)
        if digit == "3":
            newphone = phone.replace("3", "2",1)
            print(newphone)
            newphone = phone.replace("3", "6",1)
            print(newphone)
        if digit == "4":
            newphone = phone.replace("4", "1",1)
            print(newphone)
            newphone = phone.replace("4", "5",1)
            print(newphone)
            newphone = phone.replace("4", "7",1)
            print(newphone)
        if digit == "5":
            newphone = phone.replace("5", "2",1)
            print(newphone)
            newphone = phone.replace("5", "4",1)
            print(newphone)
            newphone = phone.replace("5", "6",1)
            print(newphone)
            newphone = phone.replace("5", "8",1)
            print(newphone)
        if digit == "6":
            newphone = phone.replace("6", "3",1)
            print(newphone)
            newphone = phone.replace("6", "5",1)
            print(newphone)
            newphone = phone.replace("6", "9",1)
            print(newphone)
        if digit == "7":
            newphone = phone.replace("7", "4",1)
            print(newphone)
            newphone = phone.replace("7", "8",1)
            print(newphone)
        if digit == "8":
            newphone = phone.replace("8", "5",1)
            print(newphone)
            newphone = phone.replace("8", "7",1)
            print(newphone)
            newphone = phone.replace("8", "9",1)
            print(newphone)
            newphone = phone.replace("8", "0",1)
            print(newphone)
        if digit == "9":
            newphone = phone.replace("9", "6",1)
            print(newphone)
            newphone = phone.replace("9", "8",1)
            print(newphone)
        if digit == "0":
            newphone = phone.replace("0", "8",1)
            print(newphone)

This didn’t work and there must be a more elegant solution and probably easier solution. Any help would be appreciated, thanks!

Asked By: Jacar

||

Answers:

To replace a character at a specific position, don’t use replace(), since that replaces the first N matches of the character, not the one at the current position of the loop. Use slices.

If the current index of the loop is i, use:

newphone = phone[:i] + new_character + phone[i+1:]
Answered By: Barmar

Here is a solution of full code based on @Barmar’s answer.

perm = { 
'0': ['8'], 
'1': ['2','4'], 
'2': ['1','3','5'], 
'3': ["2","6"],
'4': ["1","5","7"],
'5': ["2","4","6","8"],
'6': ["3","5","9"],
'7': ["4","8"],
'8': ["5","7","9","0"],
'9': ["6","8"],
}    # this is the code table

def myfunc(phone:str) -> list:
    return [ "{}{}{}".format(phone[:i],c,phone[i+1:]) for i in range(len(phone)) for c in perm[phone[i]] ]

Or a more readable version if needed

def myfunc(phone:str) -> list:
    rlt = []                       # result in this list
    for i in range(len(phone)):    # for each phone number digit
        for c in perm[phone[i]]:   # for each its replacement
            rlt.append("{}{}{}".format(phone[:i],c,phone[i+1:]))
    return rlt;
Answered By: Xin Cheng
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.