如何在不使用正则表达式的情况下从python中的字符串中提取数字?我见过isinstance
,但数字几乎可以更改为任何数字。有什么想法吗?
https://www.investopedia.com/articles/retirement/?page=6
答案 0 :(得分:2)
这有点冗长,但是我会为此使用url解析。与正则表达式相比,它的优点是您可以免费获得更具可读性的代码进行一些输入验证。
>>> from urllib.parse import urlparse, parse_qs
>>> url = 'https://www.investopedia.com/articles/retirement/?page=6'
>>> parsed = urlparse(url)
>>> query = parse_qs(parsed.query)
>>> [page] = query['page']
>>> int(page)
6
答案 1 :(得分:1)
如果url
始终采用最后只有数字的格式,则可以执行以下操作:
s = 'https://www.investopedia.com/articles/retirement/?page=25'
new = []
k = list(s)
[new.append(i) for i in k if i.isdigit()]
print(''.join(new))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 isdigit.py 25
答案 2 :(得分:1)
您可以使用以下命令在字符串的任意位置提取连续的数字组:
from itertools import groupby
url = 'https://www.investopedia.com/articles/retirement/?page=6&limit=10&offset=15'
print([int(''.join(group)) for key, group in groupby(iterable=url, key=lambda e: e.isdigit()) if key])
输出
[6, 10, 15]
答案 3 :(得分:1)
这假定不存在多个整数块(例如www.something212.com/page=?13
)
您可以尝试使用列表推导和str.isdigit()
url = 'https://www.investopedia.com/articles/retirement/?page=6'
digits = [d for d in url if d.isdigit()]
digit = ''.join(digits)
digit
>>> 6
已编辑:现在可用于9以上的数字
答案 4 :(得分:0)
我知道您不需要.p1 { margin-bottom: 10px;}
.p2 { margin-bottom: 10px;}
,但实际上它非常强大。在后台,大多数库都使用func addGesture() {
// Gesture recognizers
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeAction(swipe:)))
leftSwipe.direction = UISwipeGestureRecognizer.Direction.left
self.view.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeAction(swipe:)))
rightSwipe.direction = UISwipeGestureRecognizer.Direction.right
self.view.addGestureRecognizer(rightSwipe)
let downSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeAction(swipe:)))
downSwipe.direction = UISwipeGestureRecognizer.Direction.down
self.view.addGestureRecognizer(downSwipe)
}
。这是我处理这种情况的解决方案:
re
输出为
re