Python 字符串转整数94
在 Python 中,将字符串转换为整数有以下两种主要方式:
使用 int() 函数
使用 isdigit() 和 ord() 函数
使用 int() 函数
int() 函数将字符串转换为整数。它接受一个字符串参数,并返回一个整数值。
>>> s = "123"
>>> n = int(s)
>>> print(n)
123
如果字符串包含非数字字符,int() 函数将引发 ValueError 异常。例如:
>>> s = "abc"
>>> n = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
使用 isdigit() 和 ord() 函数
对于更复杂的字符串,可以使用 isdigit() 和 ord() 函数逐个字符地将字符串转换为整数。
isdigit() 函数检查一个字符是否为数字。ord() 函数返回一个字符的 Unicode 字符代码。通过组合这两个函数,我们可以将每个字符的数字值转换为整数。
def str_to_int(s):
"""
将字符串转换为整数
Args:
s (str): 要转换的字符串
Returns:
int: 转换后的整数
"""
result = 0
for c in s:
if ():
digit = ord(c) - ord('0') # 减去 '0' 的 Unicode 字符代码
result = result * 10 + digit
return result
s = "123"
n = str_to_int(s)
print(n)
这种方法在处理包含非数字字符的字符串时更加灵活。例如:
s = "123abc"
n = str_to_int(s[:3]) # 仅获取前三个字符
print(n)
在 Python 中,将字符串转换为整数可以使用 int() 函数或 isdigit() 和 ord() 函数。选择哪种方法取决于字符串的复杂性和需要转换的部分。
2024-10-19
Java节日代码实现:从静态日期到动态管理的全方位指南
https://www.shuihudhg.cn/132964.html
PHP源码获取大全:从核心到应用,全面解析各种途径
https://www.shuihudhg.cn/132963.html
PHP 与 MySQL 数据库编程:从连接到安全实践的全面指南
https://www.shuihudhg.cn/132962.html
深入理解与高效测试:Java方法覆盖的原理、规则与实践
https://www.shuihudhg.cn/132961.html
Python IDLE文件模式:从入门到实践,高效编写与运行Python脚本
https://www.shuihudhg.cn/132960.html
热门文章
Python 格式化字符串
https://www.shuihudhg.cn/1272.html
Python 函数库:强大的工具箱,提升编程效率
https://www.shuihudhg.cn/3366.html
Python向CSV文件写入数据
https://www.shuihudhg.cn/372.html
Python 静态代码分析:提升代码质量的利器
https://www.shuihudhg.cn/4753.html
Python 文件名命名规范:最佳实践
https://www.shuihudhg.cn/5836.html