Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 "replace() method" fails to change string
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"
print (s)
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
Thanks i see the problem, but why no error message?
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."
(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:

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How can I change a string. Mike Ru 3 210 Jun-03-2020, 10:55 AM
Last Post: buran
  Change string into Dict Robin_at_Cantelli 2 1,012 Mar-05-2020, 10:37 AM
Last Post: vishalhule
  Replace string in many files in a folder metro17 8 711 Oct-16-2019, 06:46 PM
Last Post: ndc85430
  open, read and replace a string in a file Reims 0 391 Oct-02-2019, 01:30 PM
Last Post: Reims
  Read each line, replace string and save into a new file igormonteiro 2 650 Sep-15-2019, 01:24 PM
Last Post: buran
  How to run a method on an argument in a formatted string Exsul 1 262 Aug-30-2019, 01:57 AM
Last Post: Exsul
  replace white space with a string, is this pythonic? Skaperen 1 459 Jun-18-2019, 11:36 PM
Last Post: metulburr
  Replace a list or string element with a random one.. pianistseb 3 552 May-09-2019, 08:24 AM
Last Post: buran
  Replace changing string including uppercase character with lowercase character silfer 11 1,385 Mar-25-2019, 12:54 PM
Last Post: silfer
  How to use a string method on user input Exsul 2 623 Mar-17-2019, 08:12 PM
Last Post: Exsul

Forum Jump:

Users browsing this thread: 1 Guest(s)