-2

I write the code below but replace method is not working.

code:

courses = input("Please enter the courses you have taken previously with letter grades: ")
courses.replace("M","X")
print(courses)

Please enter the courses you have taken previously with letter grades:

MATH101:A;SPS101:B;CS201:B+;HIST191:D;CS204:F;CS210:S:
MATH101:A;SPS101:B;CS201:B+;HIST191:D;CS204:F;CS210:S:
Dyno Fu
  • 8,753
  • 4
  • 39
  • 64
  • The `.replace()` method does not modify the string object. It returns a modified copy. You have to reassign it to `courses` – 12944qwerty May 23 '21 at 16:59
  • 1
    Does this answer your question? [Why doesn't calling a Python string method do anything unless you assign its output?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – Omkar76 May 23 '21 at 16:59
  • Stack Overflow is not intended to replace existing tutorials and documentation. Please read the method specifications before posting a related question. – Prune May 23 '21 at 17:04

3 Answers3

1

replace won't mutate the string in place. str.replace()

courses = courses.replace("M", "X")
Dyno Fu
  • 8,753
  • 4
  • 39
  • 64
1

The replace method doesn't replace the text in original string, it returns a new one. What you need to do is -

courses = courses.replace("M", "X")
print(courses)
Terra
  • 177
  • 9
0
courses = courses.replace("M","X")

Just like 12944qwerty says, You need to reassign into courses

Kate shim
  • 13
  • 2