"replace() method" fails to change string - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: "replace() method" fails to change string (/thread-14449.html) |
"replace() method" fails to change string - pw928gts - Nov-30-2018 Hi all, New to Python and this forum so I guess i am missing something simple. Why does this string method work in the Python shell but not when used in my PyCharm program? Python version seems to make no difference. import os s = "ghghkc" s.replace("g","#") print (s) RE: "replace() method" fails to change string - woooee - Nov-30-2018 Quote:"replace() method" fails to change stringYou are wrong. The replace method did change the string, but you did not assign the return to a variable. print(s.replace("g","#")) ## string is changedhttps://www.pythoncentral.io/pythons-string-replace-method-replacing-python-strings/ RE: "replace() method" fails to change string - pw928gts - Nov-30-2018 Thanks i see the problem, but why no error message? RE: "replace() method" fails to change string - wavic - Nov-30-2018 Notice that the string type is immutable. So the str.replace method does not replace the characters in place. You have to assign the returned value to a variable: s = s.replace("g","#")There is no reason for an error. RE: "replace() method" fails to change string - nilamo - Nov-30-2018 (Nov-30-2018, 05:26 PM)pw928gts Wrote: Thanks i see the problem, but why no error message? Because there wasn't an error. What you did is completely valid. You created a new string based off of a base string, s , and a transformation (the text replace). Not assigning that new string to a variable isn't an error, except possibly a semantic error: http://interactivepython.org/runestone/static/CS152f17/GeneralIntro/SemanticErrors.html
|