从python变量中提取数字

2024-09-30 05:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我是抓取一个网站,并将结果保存在一个变量中。假设我的代码中有以下内容:

worldPopulation = [scraping and such]

现在“worldPopulation”变量包含以下内容:

545.452.432.675 

世界总人口

注意:在变量的上面和下面都有一条空白行。所以有2行是空白的

我一直在尝试提取数字并将其解析到SQLite3数据库。我使用INT作为数据类型,并尝试了以下方法:

 re.findall(r'\b\d+\b', worldPopulation)

而且

re.findall(r'\d+', worldPopulation)

两者都给了我错误,这些错误是:

Line 241, in find all
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

有人知道如何从变量中检索该数字吗?它以百万为单位,所以我不想把数字分成4组3个数字,只想把它作为一个整体


Tags: and代码restring网站错误世界数字
1条回答
网友
1楼 · 发布于 2024-09-30 05:25:07

以下内容应该对您有所帮助:

import re

worldPopulation = '545.452.432.675 Worlds Total Population'

worldPopulation_number = int(re.sub('[a-zA-Z. ]','',worldPopulation))

如果你要找的是分开的数字。这可能会帮助您:

import re

worldPopulation = '545.452.432.675 Worlds Total Population'

worldPopulation_numbers = [int(x) for x in re.sub('[a-zA-Z ]','',worldPopulation).split('.')]

相关问题 更多 >

    热门问题