Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do string replacement character with function?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import string

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

    print(result)


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

I just need the function to take the string without input, so in this form

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading