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
Question [SOLVED] How to replace characters in a string? Winfried 2 1,048 Sep-04-2024, 01:41 PM
Last Post: Winfried
  Destructor method adding in string chizzy101010 3 930 Sep-03-2024, 12:31 PM
Last Post: chizzy101010
  comtypes: how to provinde a list of string to a COM method zalanthas 0 955 Jun-26-2024, 01:27 PM
Last Post: zalanthas
  Need to replace a string with a file (HTML file) tester_V 1 1,936 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 2,408 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 2,833 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  Find and Replace numbers in String giddyhead 2 3,061 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  change string in MS word Mr_Blue 8 4,834 Sep-19-2021, 02:13 PM
Last Post: snippsat
  Replace String in multiple text-files [SOLVED] AlphaInc 5 11,225 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 8,275 Aug-07-2021, 08:16 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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