python - How to extract a leading number from a string?
问题描述
I have a couple of string and I want to split them based on the numbers in it.
Ex:
- 5Hello
- 10HelloWorld
- 16HelloWorldPython
In all these cases I want to extract the numbers that is 5, 10 and 16. The numbers could be up to infinity.
This is because I want to extract numbers and compare the length of the string whether they are equal or not.
解决方案
>>> import re
>>> re.findall(r'\d+', '5Hello')
[5]
>>> re.findall(r'\d+', '10HelloWorld')
[10]
Edit : Answer to the specific question
import re
def check_len(x):
match = re.search(r'(\d+)(\w+)', x)
return int(match[1])==len(match[2])
check_len('5hello')
True
check_len('4rabbits')
False
推荐阅读
- reactjs - 如何调试无法在 react-admin 应用程序中获取
- javascript - 循环中的 JS AddEventListener(适用于所有复选框)
- laravel - 将 Laravel Voyager 中所做的更改保存到项目中
- c - 没有“\n”,服务器端 printf() 不打印(使用套接字的 TCP 客户端-服务器)
- java - JSch 发送命令到多个 ip
- ios - WKWebView 委托没有响应委托方法调用
- sql - 当我在 SSMS 中使用 RIGHT 函数时,虽然没有多余的空间,但它给了我空白的结果
- django - 如果我们想转到上一步,如何禁用字段验证?
- yubico - Yubikey 5 NFC:获得“打包”证明声明
- amazon-s3 - 如何向经过身份验证的网站用户授予对 s3 文件的访问权限