Oct-27-2020, 09:23 PM
(This post was last modified: Oct-27-2020, 09:23 PM by deanhystad.)
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.
Of course you can also write it this way:
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', '')