Python Forum
"replace() method" fails to change string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"replace() method" fails to change string
#1
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)
Reply
#2
Quote:"replace() method" fails to change string
You 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 changed
https://www.pythoncentral.io/pythons-str...n-strings/
Reply
#3
Thanks i see the problem, but why no error message?
Reply
#4
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
(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/s...rrors.html
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 699 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,147 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,545 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  Find and Replace numbers in String giddyhead 2 1,197 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  change string in MS word Mr_Blue 8 3,215 Sep-19-2021, 02:13 PM
Last Post: snippsat
  Replace String in multiple text-files [SOLVED] AlphaInc 5 7,962 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 4,919 Aug-07-2021, 08:16 AM
Last Post: perfringo
  Question about change hex string to integer sting in the list (python 2.7) lzfneu 1 2,490 May-24-2021, 08:48 AM
Last Post: bowlofred
  How to replace on char with another in a string? korenron 3 2,293 Dec-03-2020, 07:37 AM
Last Post: korenron
  How can I change a string. Mike Ru 3 2,378 Jun-03-2020, 10:55 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020