[英]How can I get the number and the letter separately from input value in python?
I want to build a converter from Celsius (C) to Fahrenheit (F) in python.我想在 python 中构建一个从摄氏度 (C) 到华氏度 (F) 的转换器。 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.如何分别获取数字和字母(例如 36C:C 作为字符串,36 作为 int),用户必须输入 input() 内置函数,然后将它们保存在两个不同的变量中。
I tried to save 36C(example) as a list, but it didn't work, because 36C is a string.我试图将 36C(example) 保存为列表,但没有成功,因为 36C 是一个字符串。 I could save it as an int.我可以将它保存为一个整数。 But I need 36 and C separately但是我分别需要 36 和 C
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)
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注意,python 中的字符串已经是一种类似列表的东西,所以可能不需要明确地转换为一个
## ---------------------
## 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}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.