如何在 Python 中从字符串中提取数字
本教程解释了如何在 Python 中从一个字符串中获取数字。它还列出了一些示例代码,以使用不同的方法进一步澄清概念。
字符串中的数字可以通过简单的列表推导来获得。split()
方法用于将字符串转换为字符列表,isdigit()
方法用于检查通过迭代是否找到数字。
基本代码示例如下:
temp_string = "Hi my age is 32 years and 250 days12"
print(temp_string)
numbers = [int(temp)for temp in temp_string.split() if temp.isdigit()]
print(numbers)
输出:
Hi my age is 32 years and 250 days12
[32, 250]
但是,这个代码不能识别带有字母的数字。
Python 的 re
模块还提供了可以搜索字符串并提取结果的函数。re
模块提供了 findall()
方法,该方法返回所有匹配结果的列表。下面给出一个示例代码。
import re
temp_string = "Hi my age is 32 years and 250.5 days12"
print(temp_string)
print([float(s) for s in re.findall(r'-?\d+\.?\d*', temp_string)])
输出:
Hi my age is 32 years and 250.5 days12
[32.0, 250.5, 12.0]
RegEx
的解决方案对负数和正数都适用,克服了列表推导式中遇到的问题。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串