Python Forum
So simple yet not working....
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
So simple yet not working....
#11
You have to say "temperature = temperature.replace(..."
Reply
#12
(Oct-27-2020, 12:13 PM)jps2020 Wrote: I'm sorry to say it doesn't work for me, and I'm not sure why.

This is my code, where I've replaced Line 5 with your suggestion, bowlofred:

temperature = (input("Insert temperature: "))

if "f" in temperature or "F" in temperature:
temperature = temperature.upper()
temperature.replace("F", "") # this is a noop because the replaced string is not captured anywhere
print(temperature)

When I run it, I'm asked to input temperature.

I input 32F.

It then prints:

32F

So there's nothing being replaced.

Hello jps,
can you try something like this:
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)
Reply
#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
#14
Another way, just for fun:
temperature = input("Insert temperature: ")

for letter in 'FCfc':
    temperature = temperature.replace(letter, '')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple conditional not working as expected return2sender 8 1,022 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,432 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