arsalunic612
arsalunic612

Reputation: 129

a function that performs a task similar to the string.replace() method in python

i am working on this python function, which should take three parameters: The first, called the content string, can be any string. The second, called the token, should be a string containing a single character which is to be replaced in the content string. The third, should denote the new character(s) that will be in the resulting string.

I have this so far :

def myReplace(aString, token, newToken):
cnt = 0
while(cnt < len(aString)):
    if(aString[cnt] == token):
        aString[cnt] == newToken
    return aString[cnt]    
cnt+=1
#print("Couldn't find "+token+" in "+aString)
return "can not find the token you are looking for in the String"

The function is suppose to return a new string with the token letter(s) replaced by the new characters,

>>> result = myReplace("Hello world!",'l','q')
>>> print(result)
Heqqo Worqd!

but it returns only one character.

>>> myReplace("hello world", 'l', 'g')
'h'

i tried removing the 'cnt' variable as well, but this would not help.

Note: I can not use the built-in replace() method for this question.

Any help will be appreciated, its just i tried working on it and nothing seems to be working anymore.

Upvotes: 0

Views: 115

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174642

The basic problem you have is that this line aString[cnt] == newToken is doing a comparison, not an assignment.

However, a bigger issue is that in Python, strings are immutable. They cannot be modified.

To fix this, you need to build a new object with the replacements and then convert it back to a string.

Here is one option, which builds a list with the replacements, then returns a string:

def replace_token(string, token, replacement):
   replaced = []
   for character in s:
      if character != token:
          replaced.append(character)
      else:
          replaced.append(replacement)

   return ''.join(replaced)

You can also build a string, but this is not recommended in the real world as this operation is highly inefficient:

def replace_token(string, token, replacement):
     replaced = ''
     for character in s:
         if character != token:
             replaced += character
         else:
             replaced += token
     return replaced

Upvotes: 1

Related Questions