Home > database >  I wanna replace letters from a string in python
I wanna replace letters from a string in python

Time:05-03

I want to have every letter of the alphabet be replaced with another letter like "python" would be "lkodna" like

S = "python"
T = s.replace('a','b')#i do this for every letter in the alphabet
Print(t)

Now obviously there is not a in python but when it tries to replace a letter that is not in the word it just doesn't do anything or messes up anyone know of a way to have it that every letter of the alphabet is replaced with a different one so that no matter the word you type it always changes the letters that are in the word and ignores the rest

CodePudding user response:

If you just want to change the different characters at a random index in a string the below function will help. This script will ask for the string you input and the total number of letters you want to change in the string with random characters, and this will print the modified string as needed.

import random
import string

Method to change N characters from a string with random characters.

def randomlyChangeNChar(word, value):

    length = len(word)
    word = list(word)
    # This will select the two distinct index for us to replace
    k = random.sample(range(0,length),value)
    for index in k:
        # This will replace the characters at the specified index with 
        # the generated characters
        word[index] = random.choice(string.ascii_lowercase)
    # Finally print the string in the modified format.
    print("" . join(word))

# Get the string to be modified
string_to_modify = raw_input("Enter the string to be replaced...\n")

# get the number of places that needed to be randomly replaced
total_places = input("Enter the total places that needs to be modified...\n")

# Function to replace 'n' characters at random
randomlyChangeNChar(string_to_modify, total_places)

CodePudding user response:

It doesn't do anything if the letter is not in the string because it just isn't there. It just logically makes no sense (please reply for more information on what you mean.) The full code (if you want it):

    # Dictionary for all letter replacements
    replacements = {"A": "some letter", "a": "some letter", ...} # do it for every letter. "Some letter should be replaced with a string of your choice.
    # Code
    string = "python"

    for letter in string:
        string = string.replace(letter, replacements.get(letter))

    print(string)

CodePudding user response:

Use a translation table and str.translate() for this problem. It is much better suited for the task, easier to maintain, and much more performant for anything but trivial substitutions.

S = "python"
trans_table = str.maketrans("python", "lkodna")
T = S.translate(trans_table)
Print(T)

You'll need to fill in the other mappings.

  • Related