Bottom Page

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)
Quote
#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/
Quote
#3
Thanks i see the problem, but why no error message?
Quote
#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
Quote
#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
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Replace string in many files in a folder metro17 8 323 Oct-16-2019, 06:46 PM
Last Post: ndc85430
  open, read and replace a string in a file Reims 0 116 Oct-02-2019, 01:30 PM
Last Post: Reims
  Read each line, replace string and save into a new file igormonteiro 2 229 Sep-15-2019, 01:24 PM
Last Post: buran
  How to run a method on an argument in a formatted string Exsul 1 90 Aug-30-2019, 01:57 AM
Last Post: Exsul
  replace white space with a string, is this pythonic? Skaperen 1 248 Jun-18-2019, 11:36 PM
Last Post: metulburr
  Replace a list or string element with a random one.. pianistseb 3 322 May-09-2019, 08:24 AM
Last Post: buran
  Replace changing string including uppercase character with lowercase character silfer 11 810 Mar-25-2019, 12:54 PM
Last Post: silfer
  How to use a string method on user input Exsul 2 388 Mar-17-2019, 08:12 PM
Last Post: Exsul
  String Method 'find(...)'. ClassicalSoul 3 357 Feb-27-2019, 12:24 PM
Last Post: buran
  Word replace with string dabozz 1 373 Feb-13-2019, 03:11 PM
Last Post: ichabod801

Forum Jump:


Users browsing this thread: 1 Guest(s)