temp = input("Please enter the tempreture. ")
temp2 = temp[0,1]
if temp[2] or temp[3] == "C" or "c":
new = (temp2*9/5)+32
print(temp + " converted into Farenheit is " + new + ".")
elif temp[2] or temp[3] == "F" or "f":
print(" ")
else:
print("You have done something wrong?")
这是家庭作业,我想使用输入来转换温度。输入为77C或77F。有什么方法可以将其设置为77,以便可以在计算中使用它?
答案 0 :(得分:0)
您必须实现切片才能实现此目的。
首先让我们定义温度
temp1 = '31c'
然后我们可以通过执行以下操作将31转换为整数
temp1 = int(temp1[:2])
答案 1 :(得分:0)
这里有几件事在玩:
[-1]
,例如:example_string[-1]
。负索引从末尾开始倒数。负索引也可以用在切片中:example_string[2:-1]
。int
的方式如下:int(example_string)
。尝试执行未定义的强制转换会导致ValueError
。因为这是家庭作业,所以我不会为您破坏最终结果。
答案 2 :(得分:0)
如果要删除最后一个字符,可以使用索引为负的字符串切片:
if tempStr[-1].lower == 'c':
tempStr = tempStr[:-1]
切片是两个值,以冒号分隔。第一个冒号之前的值是第一个字符,冒号后面的值是最后一个字符(实际上是最后一个字符之后的字符)。负索引从字符串的后面开始倒数,而不是从前面开始。
或者,您可能想删除'C'或'F'并转换其余部分。
tempStr=tempStr.upper();
if 'F' in tempStr.upper():
tempStr=tempStr.upper().replace('F','')
temp_C = int((int(tempStr)-32)*5/9)