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

Python中如何将上标数字字符(如'³')转换为整数?

解决Unicode特殊数字字符无法用int()转换的问题

问题原因

str.isdigit()返回True是因为Unicode标准中,上标数字(如'³',Unicode码点U+00B3)被归类为数字字符,但Python的int()函数仅支持解析ASCII范围内的'0'-'9'字符,因此直接转换会抛出ValueError。

解决方案

方法1:使用unicodedata模块(通用单字符处理)

Python的unicodedata.digit()方法可以直接返回Unicode字符对应的十进制整数值,适用于单个特殊数字字符的转换:

import unicodedata

x = '³'
num = unicodedata.digit(x)
print(num)  # 输出:3

如果不确定字符是否能转换,可添加异常处理:

import unicodedata

def convert_single_digit(char):
    try:
        return unicodedata.digit(char)
    except ValueError:
        # 处理无法转换的字符
        return None

print(convert_single_digit('³'))  # 3
print(convert_single_digit('a'))  # None

方法2:构建字符映射表(高效已知范围处理)

如果仅需处理特定的特殊数字(如上标、下标数字),可以直接构建映射表,转换效率更高:

special_digit_map = {
    '¹': 1, '²': 2, '³': 3, '⁴': 4, '⁵': 5,
    '⁶': 6, '⁷': 7, '⁸': 8, '⁹': 9, '⁰': 0,
    '₁': 1, '₂': 2, '₃': 3, '₄': 4, '₅': 5,
    '₆': 6, '₇': 7, '₈': 8, '₉': 9, '₀': 0
}

x = '³'
num = special_digit_map[x]
print(num)  # 输出:3

方法3:正则替换处理字符串(多字符场景)

如果需要处理包含特殊数字的字符串,可通过正则替换将特殊字符转为常规数字后再用int()转换:

import re

special_digit_map = {
    '¹': '1', '²': '2', '³': '3', '⁴': '4', '⁵': '5',
    '⁶': '6', '⁷': '7', '⁸': '8', '⁹': '9', '⁰': '0'
}

def convert_special_digit_string(s):
    # 生成正则匹配模式
    pattern = re.compile('|'.join(re.escape(char) for char in special_digit_map.keys()))
    # 替换特殊字符为常规数字后转整数
    return int(pattern.sub(lambda match: special_digit_map[match.group()], s))

# 测试单个字符
print(convert_special_digit_string('³'))  # 3
# 测试多字符字符串
print(convert_special_digit_string('¹²³'))  # 123

扩展:处理更多Unicode数字类型

如果需要处理罗马数字、分数等其他Unicode数字,可使用unicodedata.numeric()方法(返回浮点数,需转为整数):

import unicodedata

# 罗马数字8
x = 'Ⅷ'
print(int(unicodedata.numeric(x)))  # 8
# 分数½
y = '½'
print(int(unicodedata.numeric(y) * 2))  # 1(根据需求处理)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:05:22