You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

将字符串转换为整数的Python命令是什么?

字符串转整数的Python方法及代码问题修复

嘿,先直接回答你最关心的问题:

将字符串转换为整数的Python命令

在Python里,把字符串转成整数用的是int()函数,用法很简单:int(目标字符串)。比如int("2024")会返回整数2024。不过要注意,这个字符串必须是纯数字组成的有效整数格式,要是输入像"December"这种非数字字符串,int()就会报错,也就是你遇到的ValueError啦。


你的代码报错原因及修复方案

你碰到的错误,核心问题是你输入了月份的英文名称(比如"December"),但int()根本没法把这个单词转换成整数。除此之外,你的代码还有几个小问题需要调整:

  • 出生年份的计算逻辑完全错了:Birth_Year = 2022 - Year + Month + Date这行公式完全不符合逻辑,出生年份就是你输入的Year本身呀?如果是想算年龄的话,应该是当前年份 - 出生年份,比如2024 - Year(假设现在是2024年)。
  • 字符串和整数拼接报错:最后一行print("Your DOB is..." + Birth_Year + "!")里,Birth_Year是整数,Python不允许直接把整数和字符串用+拼接,得先把整数转成字符串,用str(Birth_Year)才行。
  • 冗余变量:你定义了January = 1这类月份变量,但代码里完全没用到,属于多余的代码,可以删掉。

修复后的代码示例

print("DOB:")
# 给用户明确提示,输入数字形式的月份
Year = int(input("Year? (比如 1995) "))
Month = int(input("Month? (比如 12 代表 December) "))
Date = int(input("Date? (比如 20) "))

# 如果要输出出生年份,直接用输入的Year即可
birth_year = Year
# 如果要计算年龄,用当前年份减去出生年份
current_year = 2024
age = current_year - birth_year

# 打印时把整数转成字符串再拼接
print(f"Your birth year is {birth_year}!")
# 也可以用str()转换:print("Your birth year is " + str(birth_year) + "!")
print(f"Your current age is {age}!")

进阶:允许输入月份英文名称

如果你想让用户可以输入"December"这类英文月份,那得先把输入的字符串映射成对应的数字,可以用字典来实现:

print("DOB:")
Year = int(input("Year? (比如 1995) "))

# 定义月份名称到数字的映射字典
month_dict = {
    "january": 1,
    "february": 2,
    "march": 3,
    "april": 4,
    "may": 5,
    "june": 6,
    "july": 7,
    "august": 8,
    "september": 9,
    "october": 10,
    "november": 11,
    "december": 12
}

month_input = input("Month? (可以输入英文比如 December 或数字 12) ").lower()
# 判断输入是数字还是英文月份
if month_input.isdigit():
    Month = int(month_input)
else:
    # 从字典里取对应的数字,默认返回0表示输入无效
    Month = month_dict.get(month_input, 0)
    if Month == 0:
        print("输入的月份无效哦,请重新运行程序输入正确的月份!")
        exit()

Date = int(input("Date? (比如 20) "))

birth_year = Year
current_year = 2024
age = current_year - birth_year

print(f"Your birth year is {birth_year}!")
print(f"Your current age is {age}!")

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

火山引擎 最新活动