1

I created this function:

def change(string,word1,word2):
    string=string.split(" ")
    for x in string:
        if x==word1:
            x=word2
    string=" ".join(string)
    print (string)

v1= "X went to buy food. X forgot his car keys in the car."

change(v1,"X","Y")

But the output is still:

"X went to buy food. X forgot his car keys in the car."

The output should be:

"Y went to buy food. Y forgot his car keys in the car."

What is wrong with the code? Why is it not working?

Edit: Guys, Thanks for all solutions, but I wonder Why is this not working? This is so that I don't do similar mistakes in future.

lansXp
  • 13
  • 1
  • 6
  • 1
    can't you use replace? like `v1.replace('X','Y')` – Kuldeep Singh Sidhu Jun 14 '20 at 12:58
  • 2
    Strings are immutable, and assignment to bare names does not mutate in the first place. Use ``str.replace`` instead. – MisterMiyagi Jun 14 '20 at 12:59
  • I think defining `change` like this: `def change(string,word1,word2): print(string.replace(word1, word2))` is somewhat better – Anwarvic Jun 14 '20 at 13:01
  • How should the ideal function process this sentence: "X forgot the alphabet ends with 3 chars XYZ"? What I mean is, do you want actual word replacement? Would "XYZ" be preserved as "XYZ"? That would be proper word replacement. – Peaceful James Jun 14 '20 at 13:02

5 Answers5

-1

Python has a built-in for this one, .replace():

"The orange orange gleamed of orange.".replace("orange", "purple")
# "The purple purple gleamed of purple."
Xiddoc
  • 3,369
  • 3
  • 11
  • 37
-1

try a simple replacement:

mystring = "X went to buy food. X forgot his car keys in the car."
new_string = mystring.replace("X","Y")

print(mystring)
print(new_string)

output:

X went to buy food. X forgot his car keys in the car.
Y went to buy food. Y forgot his car keys in the car.

or just change your method a little bit:

def change(string,word1,word2):
    string=string.split(" ")
    newstring=[]
    for x in string:
        #print(x)
        if x == word1:
            x=word2
        newstring.append(x)    
    newstring=" ".join(newstring)
    print (newstring)


change(mystring,"X","Y")

output:

Y went to buy food. Y forgot his car keys in the car.
Stefan Schulz
  • 533
  • 3
  • 8
-2

Try this:

def change(string,word1,word2):
    return word2.join(string.split(word1))
goodvibration
  • 5,980
  • 4
  • 28
  • 61
-2
def change(string, word1, word2):
    string = string.split(" ")
    for x in range(len(string)):
        if string[x] == word1:
            string[x] = word2
    string = " ".join(string)
    print(string)

Change the for loop as mentioned above will give your expected output.

-3
def change(string,word1,word2):
    changed_string = string.replace(word1,word2)
    print(changed_string)
v1= "X went to buy food. X forgot his car keys in the car."

change(v1,"X","Y")
  • 10
    Mind that the question is "What is wrong with the code? Why is it not working?". – MisterMiyagi Jun 14 '20 at 13:16
  • 4
    Please add an explanation. Why was the OP having the problem? How does your code solve this problem? – Run_Script Jun 14 '20 at 19:37
  • 2
    While this code may resolve the OP's issue, it's better to include an explanation on how your code addresses the OP's issue. This way, future visitors can learn from your post, & apply it to their own code. SO is not a coding service, but a resource for knowledge. High quality, complete answers reinforce this idea, and are more likely to be upvoted. These features, plus the requirement that all posts be self-contained, are some strengths of SO as a platform that differentiates us from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – SherylHohman Jun 14 '20 at 23:30
  • 2
    Also, if your "Answer" address the question posted by the OP, your response may be considered a non-answer, and could be considered for removal by the community. Please consider 'editing' to meet SO guidelines for Answers, or consider posting aa Comment instead. Visit [guidelines](https://StackOverflow.com/help/how-to-answer) and [help](https://StackOverflow.com/help) for more info. – SherylHohman Jun 14 '20 at 23:38