Home > Blockchain >  How can I exchange a specific letter in a string using a function?
How can I exchange a specific letter in a string using a function?

Time:11-29

So I have this function swapplaces(s, c, r) that takes a string s, a string c that has length 1, and a string r that has length 1. The function will return a new string where all occurrences of the character c is replaced by r. The upper- and lower-case letters are treated differently.

Examples

swapplaces("let","l","g") == "get"
swappalces("chip","c","s") == "ship"
swapplaces("lay low for lola","l","s") == "say sow for sosa"
swapplaces("OcapudoliciOus", "O", "e") == "ecapudolicieus"

Here is my code so far

def listToString(s): 
    str1 = " " 
    return (str1.join(s))
def swapplaces(s,c,r):
    q = list(s)
    for c in q:
       q.replace(c,r)
    return listToString(q)

However, my code doesn't work at all, what changes should I make??

CodePudding user response:

As mentioned, x.replace(y, z) will replace all instances of y in string x with character z.

Side note: Be careful with your variable naming. The iterator for c in q shares the same name as the input variable c for the swapplaces() function. This means that by the time you get to q.replace(c,r) your 'c' is no longer the function input variable but rather the iterator. Consider:

def test(a):
    q = list(a)
    print(f'Before {a}')
    for a in q:
        print(a)
    print(f'After {a}')

test("Hello")

Output

Before Hello
H
e
l
l
o
After o

CodePudding user response:

Does your function need to be as complex as it is? Has your teacher precluded you from using certain functions or methods? The simplest solution that I can see would be:

def swapplaces(s, c, r):
    return s.replace(c, r)

Is this sufficient? I'm guessing you have certain constraints that you are not sharing. Is this true? Are you required to process the input string as a list?

You could make it a little more robust by making sure that c and r are only one char...

def swapplaces(s, c, r):
    c, r = c[:1], r[:1]
    return s.replace(c, r)

Also, your listToString() has a bug. I would change:

str1 = " "

to:

str1 = ""  

CodePudding user response:

Here is the correction for your code.

def listToString(s): 
    str1 = "" 
    return (str1.join(s))

def swapplaces(s,c,r):
    q = s
    for c in q:
       q.replace(c,r)
    return listToString(q)
  • Related