Python Forum
So simple yet not working....
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
So simple yet not working....
#13
The str.replace() method is a liar. The name makes it sound like it replaces substrings in a string. IT DOES NOT!!! str.replace() creates a new string from the source string. The substrings are replaced in the new string.

This is why your code fails. If temperature == "32 F", temperature.replace("F", "") returns the string "32 ". However, the string temperature is still "32 F". If I call temperature.replace("f", "") it returns "32 F" because there were no "f"'s in temperature.

This code works because the result string is saved and used as the source string in the next step.
temperature = input("Insert temperature: ")
 
new_str = temperature.replace('F', '')
new_str = new_str.replace('C', '')
new_str = new_str.replace('f', '')
new_str = new_str.replace('c', '')
print(new_str)
I prefer not introducing new strings and would write it like this.
temperature = input("Insert temperature: ")
 
temperature = temperature.replace('F', '')
temperature = temperature.replace('C', '')
temperature = temperature.replace('f', '')
temperature = temperature.replace('c', '')
print(new_str)[/python]
Of course you can also write it this way:
temperature = input("Insert temperature: ")
 
temperature = temperature.replace('F', '').replace('C', '').replace('f', '').replace('c', '')
Reply


Messages In This Thread
So simple yet not working.... - by giladal - Oct-26-2020, 10:19 PM
RE: So simple yet not working.... - by Askic - Oct-26-2020, 10:37 PM
RE: So simple yet not working.... - by giladal - Oct-26-2020, 10:41 PM
RE: So simple yet not working.... - by Askic - Oct-26-2020, 10:44 PM
RE: So simple yet not working.... - by giladal - Oct-26-2020, 10:53 PM
RE: So simple yet not working.... - by bowlofred - Oct-26-2020, 10:39 PM
RE: So simple yet not working.... - by giladal - Oct-26-2020, 10:49 PM
RE: So simple yet not working.... - by bowlofred - Oct-26-2020, 11:10 PM
RE: So simple yet not working.... - by giladal - Oct-27-2020, 07:05 AM
RE: So simple yet not working.... - by jps2020 - Oct-27-2020, 12:13 PM
RE: So simple yet not working.... - by Askic - Oct-27-2020, 04:59 PM
RE: So simple yet not working.... - by jefsummers - Oct-27-2020, 02:28 PM
RE: So simple yet not working.... - by deanhystad - Oct-27-2020, 09:23 PM
RE: So simple yet not working.... - by GOTO10 - Oct-27-2020, 09:31 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple conditional not working as expected return2sender 8 1,174 Aug-27-2023, 10:39 PM
Last Post: return2sender
  Why isn't this working. I've made it as simple as posible gcryall_Forum 3 2,554 Mar-10-2019, 03:07 PM
Last Post: gcryall_Forum

Forum Jump:

User Panel Messages

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