Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can i use or in .replace function?

I’m trying to make a temperature converter. It convert Celsius to Fahrenheit and vice versa. The code I wrote is:

user_input = input("Insert the temperature you would like to convert: ")
user_num = user_input.replace('F' or 'C', '')
user_temp = float(user_num)


if ('F' in user_input or 'f' in user_input):
  print(((user_temp - 32) * 5/9), 'C') # conversion from F to C

elif ('C' in user_input or 'c' in user_input): 
  print(((user_temp * 9/5) + 32), 'F') # conversion fron C to F

else: 
  print("Try again.")

I can convert Fahrenheit to Celsius, but can’t do the opposite.
When I try to convert c to f i get
user_temp = float(user_num) ValueError: could not convert string to float: '36C'

Also, I want to make the code so it replaces either ‘F’ or ‘f’ and ‘C’ or ‘c’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I can fix in order to make this work?

>Solution :

'F' or 'C' just evaluates to 'F'. I don’t think this is what you want. You can either replace twice:

user_num = user_input.replace('F', '').replace('C', '')

or use a RegEx:

import re

user_num = re.sub('F|C', '', user_input)

I think your later 'f' and 'c' should probably be capitalised.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading