Home > front end >  How can I get the number and the letter separately from input value in python?
How can I get the number and the letter separately from input value in python?

Time:12-22

I want to build a converter from Celsius (C) to Fahrenheit (F) in python. How can I get the number and the letter (ex. 36C: C as string and 36 as an int) separately the user has to input in an input() built-in function and then save them in two different variables.

I tried to save 36C(example) as a list, but it didn't work, because 36C is a string. I could save it as an int. But I need 36 and C separately

CodePudding user response:

You could use a regex with something like:

import re

# ask input
inp = input()

# get digits, optional space(s), unit
m = re.match('(\d )\s*([CF])', inp)

# if the match failed, input is invalid
if not m:
    print('invalid input')
# else get the 2 parts
else:
    value, unit = m.groups()
    value = int(value)
    print(value, unit)

CodePudding user response:

Split the inputs uisng re and then unpack list - re

import re
tem = input()
sp = re.split('(\d )',tem)
sp = list(filter(None, sp))#remove empty elemnt
temp, degree_cel = sp[0], sp[1]
print(temp)
print(degree_cel)

output #

36
C

CodePudding user response:

Regex is of course a very valid way to parse the user's input. If you wanted to parse it without using that library, we could also just assume the last charater of the user input is the measure:

Note, strings in python are already a sort of list like thing so probably no need to convert to one explicitely

## ---------------------
## get some input from the user
## ---------------------
temp_as_string = input().strip()
if not temp_as_string:
    raise ValueError("no input given")
## ---------------------

## ---------------------
## let's assume the last character is the units
## ---------------------
units = temp_as_string[-1].lower()
if units not in ["c", "f"]:
    raise ValueError("bad units")
## ---------------------

## ---------------------
## everything before the units is then the measure
## ---------------------
measure = temp_as_string[:-1]
if not measure:
    raise ValueError("bad measure")
measure = int(measure)
## ---------------------

print(f"{measure} degrees {units}")
  • Related