Home > Net >  How to do string replacement character with function?
How to do string replacement character with function?

Time:11-20

I am trying to create a function that takes 3 string parameters and replaces the characters.

The first parameter is the word, the second is the letter I want to replace, and the third is the letter I want it replaced with. This has to work for any string.

Here is the code I have so far:

def replace_letter(phrase,letter,replace):
    phrase = phrase.replace(letter,replace)

    print(replace_letter(phrase,letter,replace))

def word_and_phrase_processing():
    phrase=input("Enter the phrase: ")
    letter=input("Letter to replace? ")
    replace=input("Replace it with? ")
    replace_letter(phrase,letter,replace)

 word_and_phrase_processing()

CodePudding user response:

Here is a commented & corrected version of your code:

#import string # not used

def replace_letter(phrase,l,r):
    #phrase = f"{phrase}"         # useless
    result = phrase.replace(l, r) # use variable names, not strings
    return result
    #print(result)  # not evaluated (after return)

print(replace_letter("cat","a","o"))

output cot

CodePudding user response:

The correct code shall be:

import string

def replace_letter(phrase,l,r):

    phrase = f"{phrase}"
    result = phrase.replace(l, r)
    return result

print(replace_letter("cat","a","o"))

I modified two things:

  1. Print result is not in the right place (either you put it before the return statement or put it as I did as a print of function call)

  2. When you are using the function arguments inside the function definition you mentioned:

    result = phrase.replace("l", "r")

This tells python to replace the character "l" with character "r". What I did is to remove " from your code to tell Python to use l and r variables not the constants "l" and "r".

  • Related