【问题标题】:Is there any way to set a variable to be only the first 2 characters of another variable and set it as an integer有没有办法将变量设置为仅另一个变量的前 2 个字符并将其设置为整数
【发布时间】:2021-01-24 23:32:07
【问题描述】:
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 作为整数,以便在计算中使用它?

【问题讨论】:

标签: python


【解决方案1】:

您必须实施切片才能完成此操作。

首先让我们定义我们的温度

temp1 = '31c'

然后我们可以通过以下操作将 31 转换为整数

temp1 = int(temp1[:2])

【讨论】:

    【解决方案2】:

    这里有几件事在起作用:

    • 要获取字符串的最后一个字符,请使用索引[-1],例如:example_string[-1]。负索引从末尾倒数。也可以在切片中使用负索引:example_string[2:-1]
    • 要检查字母的身份,首先将其转换为小写,然后将结果与字母的小写版本进行比较。
    • 类型之间的更改称为转换。转换为int 的方法如下:int(example_string)。尝试执行未定义的强制转换将导致 ValueError

    因为这是作业,所以我不会为你破坏最终结果。

    【讨论】:

      【解决方案3】:

      如果要删除最后一个字符,可以使用带负索引的字符串切片:

      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)
      

      【讨论】:

        猜你喜欢
        • 2019-12-13
        • 1970-01-01
        • 2019-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        • 2019-05-23
        相关资源
        最近更新 更多