使用int()函数可将字符串转为整数,支持指定进制和自动忽略空白字符,但非法字符会引发ValueError;可通过try-except处理异常,或用正则提取数字;浮点字符串需先转float再转int,可选择截断、四舍五入等策略;大批量转换时推荐map()或numpy以提升性能。

在Python中,将字符串转换为整数的核心方法是使用内置的
int()
ValueError
Python 提供了一个直观且强大的内置函数
int()
# 基本转换
s_num = "12345"
i_num = int(s_num)
print(f"字符串 '{s_num}' 转换为整数:{i_num}, 类型:{type(i_num)}") # 输出:12345, 类型:<class 'int'>
# 负数转换
s_neg_num = "-678"
i_neg_num = int(s_neg_num)
print(f"字符串 '{s_neg_num}' 转换为整数:{i_neg_num}") # 输出:-678
# 带有前导或尾随空格的字符串
# int() 函数会自动忽略前导和尾随的空白字符
s_padded_num = " 9012 "
i_padded_num = int(s_padded_num)
print(f"字符串 '{s_padded_num}' 转换为整数:{i_padded_num}") # 输出:9012
# 指定进制进行转换
# int() 函数还可以接受第二个可选参数 `base`,用于指定字符串表示的数字的进制
s_binary = "1011" # 二进制的1011是十进制的11
i_binary = int(s_binary, 2)
print(f"二进制字符串 '{s_binary}' 转换为整数:{i_binary}") # 输出:11
s_hex = "FF" # 十六进制的FF是十进制的255
i_hex = int(s_hex, 16)
print(f"十六进制字符串 '{s_hex}' 转换为整数:{i_hex}") # 输出:255然而,当字符串内容不符合整数格式时,
int()
ValueError
# 错误示例:包含非数字字符
try:
int("12a3")
except ValueError as e:
print(f"尝试转换 '12a3' 失败:{e}") # 输出:invalid literal for int() with base 10: '12a3'
# 错误示例:空字符串
try:
int("")
except ValueError as e:
print(f"尝试转换 '' 失败:{e}") # 输出:invalid literal for int() with base 10: ''
# 错误示例:浮点数字符串(直接转换)
try:
int("3.14")
except ValueError as e:
print(f"尝试转换 '3.14' 失败:{e}") # 输出:invalid literal for int() with base 10: '3.14'为了稳健地处理这些潜在的错误,通常会结合
try-except
ValueError
立即学习“Python免费学习笔记(深入)”;
def safe_str_to_int(s):
try:
return int(s)
except ValueError:
print(f"警告:无法将 '{s}' 转换为整数,返回 None。")
return None
print(safe_str_to_int("123")) # 输出:123
print(safe_str_to_int("abc")) # 输出:警告:无法将 'abc' 转换为整数,返回 None。 None
print(safe_str_to_int("12.5")) # 输出:警告:无法将 '12.5' 转换为整数,返回 None。 None在实际开发中,我们经常会遇到字符串中夹杂着数字和非数字字符的情况,比如从用户输入、文件读取或网页抓取中获取的“价格:120元”、“温度25℃”这类数据。直接使用
int()
一种常见且有效的方法是使用正则表达式(
re
import re
def extract_and_convert_int(text):
# 匹配字符串开头可选的负号,后面跟着一个或多个数字
# 或者只匹配一个或多个数字
match = re.search(r'^-?\d+', text)
if match:
try:
return int(match.group(0))
except ValueError:
# 理论上,如果正则表达式匹配成功,int() 不应该失败,
# 但为了极致的健壮性,这里依然保留。
print(f"内部错误:'{match.group(0)}' 匹配成功但转换失败。")
return None
else:
print(f"字符串 '{text}' 中未找到可转换的整数部分。")
return None
print(extract_and_convert_int("价格:120元")) # 输出:120
print(extract_and_convert_int("温度-25℃")) # 输出:-25
print(extract_and_convert_int("订单号ABC123XYZ")) # 输出:123
print(extract_and_convert_int("没有数字的字符串")) # 输出:字符串 '没有数字的字符串' 中未找到可转换的整数部分。 None
print(extract_and_convert_int("123.45元")) # 输出:123 (只提取了整数部分)
print(extract_and_convert_int("-50.5度")) # 输出:-50上述
re.search(r'^-?\d+', text)
-?
\d+
r'-?\d+'
另一种思路是,如果知道字符串中只有数字和一些特定的非数字字符需要移除,可以使用
str.replace()
re.sub()
def clean_and_convert(text, chars_to_remove='元℃'):
cleaned_text = text
for char in chars_to_remove:
cleaned_text = cleaned_text.replace(char, '')
# 移除所有非数字和非负号字符,但要小心处理负号的位置
# 更安全的做法是先尝试匹配整个数字
match = re.match(r'^-?\d+$', cleaned_text.strip())
if match:
try:
return int(match.group(0))
except ValueError:
print(f"清理后的字符串 '{cleaned_text}' 转换失败。")
return None
else:
print(f"清理后的字符串 '{cleaned_text}' 不是纯整数格式。")
return None
print(clean_and_convert("价格:120元")) # 输出:清理后的字符串 '价格:120' 不是纯整数格式。 None (因为'价格:'没被移除)
print(clean_and_convert("120元", chars_to_remove='元')) # 输出:120
print(clean_and_convert("-25℃", chars_to_remove='℃')) # 输出:-25可以看出,
clean_and_convert
当字符串代表的是浮点数(如 "3.14" 或 "10.99"),而我们最终需要一个整数时,直接使用
int()
ValueError
直接截断 (Truncation): 这是最简单直接的方式,Python 的
int()
s_float1 = "3.14"
s_float2 = "3.99"
s_float3 = "-2.7"
i_trunc1 = int(float(s_float1))
i_trunc2 = int(float(s_float2))
i_trunc3 = int(float(s_float3))
print(f"'{s_float1}' 截断后:{i_trunc1}") # 输出:3
print(f"'{s_float2}' 截断后:{i_trunc2}") # 输出:3
print(f"'{s_float3}' 截断后:{i_trunc3}") # 输出:-2 (注意:对于负数,是向0取整)四舍五入 (Rounding): 如果希望将浮点数四舍五入到最接近的整数,可以使用内置的
round()
round()
.5
s_float4 = "3.4"
s_float5 = "3.5"
s_float6 = "3.6"
s_float7 = "2.5" # 银行家舍入法示例
s_float8 = "-3.5"
i_round4 = int(round(float(s_float4)))
i_round5 = int(round(float(s_float5)))
i_round6 = int(round(float(s_float6)))
i_round7 = int(round(float(s_float7)))
i_round8 = int(round(float(s_float8)))
print(f"'{s_float4}' 四舍五入后:{i_round4}") # 输出:3
print(f"'{s_float5}' 四舍五入后:{i_round5}") # 输出:4 (因为3.5到4的距离和到3的距离相等,round()倾向于偶数)
print(f"'{s_float6}' 四舍五入后:{i_round6}") # 输出:4
print(f"'{s_float7}' 四舍五入后:{i_round7}") # 输出:2 (2.5到2的距离和到3的距离相等,round()倾向于偶数)
print(f"'{s_float8}' 四舍五入后:{i_round8}") # 输出:-4 (对于负数,-3.5到-4的距离和到-3的距离相等,round()倾向于偶数)如果你需要传统的“四舍五入”(即
.5
int(f + 0.5)
int(f + 0.5) if f >= 0 else int(f - 0.5)
decimal
向上取整 (Ceiling): 总是向正无穷方向取整,即无论小数部分是什么,都向上取到下一个整数。需要导入
math
import math
s_float9 = "3.14"
s_float10 = "3.99"
s_float11 = "-2.7"
s_float12 = "-2.1"
i_ceil9 = int(math.ceil(float(s_float9)))
i_ceil10 = int(math.ceil(float(s_float10)))
i_ceil11 = int(math.ceil(float(s_float11)))
i_ceil12 = int(math.ceil(float(s_float12)))
print(f"'{s_float9}' 向上取整后:{i_ceil9}") # 输出:4
print(f"'{s_float10}' 向上取整后:{i_ceil10}") # 输出:4
print(f"'{s_float11}' 向上取整后:{i_ceil11}") # 输出:-2
print(f"'{s_float12}' 向上取整后:{i_ceil12}") # 输出:-2向下取整 (Floor): 总是向负无穷方向取整,即无论小数部分是什么,都向下取到上一个整数。同样需要导入
math
import math
s_float13 = "3.14"
s_float14 = "3.99"
s_float15 = "-2.7"
s_float16 = "-2.1"
i_floor13 = int(math.floor(float(s_float13)))
i_floor14 = int(math.floor(float(s_float14)))
i_floor15 = int(math.floor(float(s_float15)))
i_floor16 = int(math.floor(float(s_float16)))
print(f"'{s_float13}' 向下取整后:{i_floor13}") # 输出:3
print(f"'{s_float14}' 向下取整后:{i_floor14}") # 输出:3
print(f"'{s_float15}' 向下取整后:{i_floor15}") # 输出:-3
print(f"'{s_float16}' 向下取整后:{i_floor16}") # 输出:-3选择哪种策略取决于具体的业务需求。如果只是简单地丢弃小数,
int(float(s))
round()
int()
math.ceil()
math.floor()
在处理少量字符串到整数的转换时,
int()
避免不必要的错误处理开销:
try-except
try-except
# 假设有一个函数可以预先检查字符串是否为纯数字
def is_numeric(s):
return s.strip().isdigit() or (s.strip().startswith('-') and s.strip()[1:].isdigit())
data_strings = ["123", "456", "abc", "789", "-100", "xyz"]
results = []
for s in data_strings:
if is_numeric(s):
results.append(int(s))
else:
# 处理非数字字符串,例如跳过或记录错误
pass
print(f"预校验后的转换结果:{results}")这种预校验的开销可能与
try-except
is_numeric
使用 map()
map()
for
list_of_strings = [str(i) for i in range(100000)] # 10万个字符串
# 使用列表推导式
import time
start_time = time.perf_counter()
ints_lc = [int(s) for s in list_of_strings]
end_time = time.perf_counter()
print(f"列表推导式耗时:{(end_time - start_time):.6f} 秒")
# 使用 map()
start_time = time.perf_counter()
ints_map = list(map(int, list_of_strings))
end_time = time.perf_counter()
print(f"map() 函数耗时:{(end_time - start_time):.6f} 秒")
# 结果通常是 map() 稍快然而,
map()
利用 numpy
numpy
numpy
numpy
import numpy as np
# 创建一个包含数字字符串的numpy数组
np_string_array = np.array([str(i) for i in range(1000000)]) # 100万个字符串
start_time = time.perf_counter()
# 使用astype() 方法进行类型转换
np_int_array = np_string_array.astype(int)
end_time = time.perf_counter()
print(f"NumPy astype() 耗时:{(end_time - start_time):.6f} 秒")
# 注意:如果字符串中包含非数字字符,astype(int) 同样会报错
# np.array(["123", "abc"]).astype(int) 会引发 ValueErrornumpy
numpy
分批处理 (Batch Processing): 对于海量数据,一次性加载所有数据并转换可能会占用过多内存。可以考虑分批读取和处理数据,例如每次读取10000行,处理完毕后再读取下一批。这有助于控制内存使用,并且在某些
以上就是python如何将字符串转换为整数_python字符串与整数类型转换技巧的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号