You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中从input输入值分离数字与字母,实现温标转换?

摄氏度/华氏度转换器实现方案

这里给你两种实用的方法来拆分输入中的数字和单位:

方法1:遍历字符串手动拆分

适合理解基础逻辑,还能处理零下温度的情况:

# 获取用户输入
temp_input = input("请输入温度(格式示例:36C 或 98F): ")

num_str = ""
unit = ""

# 遍历每个字符拆分数字和单位
for char in temp_input:
    # 匹配数字或负号(支持零下温度)
    if char.isdigit() or char == "-":
        num_str += char
    else:
        unit += char.strip()  # 去除可能的空格

# 转换数字为整数(需要小数的话可以用float)
temperature = int(num_str)
unit = unit.upper()  # 统一转为大写,避免大小写问题

# 温度转换逻辑
if unit == "C":
    fahrenheit = temperature * 9/5 + 32
    print(f"{temperature}℃ 转换为华氏度是 {fahrenheit}℉")
elif unit == "F":
    celsius = (temperature - 32) * 5/9
    print(f"{temperature}℉ 转换为摄氏度是 {celsius}℃")
else:
    print("请输入正确的单位(C或F)")

方法2:正则表达式拆分(更简洁)

如果输入格式固定为「数字+单个单位字母」,用正则能一步到位:

import re

temp_input = input("请输入温度(格式示例:36C 或 98F): ")
# 正则匹配:可选负号+数字+单位(C/F,不区分大小写)
match_result = re.match(r"^(-?\d+)([CFcf])$", temp_input)

if match_result:
    num_str = match_result.group(1)
    unit = match_result.group(2).upper()
    temperature = int(num_str)
    
    if unit == "C":
        fahrenheit = temperature * 9/5 + 32
        print(f"{temperature}℃ = {fahrenheit}℉")
    else:
        celsius = (temperature - 32) * 5/9
        print(f"{temperature}℉ = {celsius}℃")
else:
    print("输入格式错误,请按照「数字+单位」的格式输入,例如36C")

你之前直接转列表或整数失败,是因为输入是混合了数字和字母的字符串,必须先拆分出纯数字部分再转换类型,上面两种方法都能解决这个问题。

内容的提问来源于stack exchange,提问作者Indi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:50:42