Python 获取给定字符串的数字前缀
假设我们有一个字符串,其中包含开头处的数字。在本文中,我们将了解如何仅获取字符串中位于开头的固定数字部分。
使用 isdigit
isdigit 函数判断字符串的一部分是否为数字。因此,我们将使用 itertools 中的 takewhile 函数来连接字符串中每个是数字的部分。
示例
from itertools import takewhile
# Given string
stringA = "347Hello"
print("Given string : ",stringA)
# Using takewhile
res = ''.join(takewhile(str.isdigit, stringA))
# printing resultant string
print("Numeric Pefix from the string: \n", res)输出
运行以上代码将得到以下结果:
Given string : 347Hello Numeric Pefix from the string: 347
使用 re.sub
使用正则表达式模块 re,我们可以创建一个模式来仅搜索数字。搜索将仅查找字符串开头的数字。
示例
import re
# Given string
stringA = "347Hello"
print("Given string : ",stringA)
# Using re.sub
res = re.sub('\D.*', '', stringA)
# printing resultant string
print("Numeric Pefix from the string: \n", res)输出
运行以上代码将得到以下结果:
Given string : 347Hello Numeric Pefix from the string: 347
使用 re.findall
findall 函数的工作方式类似于 girl,只是我们使用加号而不是 *。
示例
import re
# Given string
stringA = "347Hello"
print("Given string : ",stringA)
# Using re.sub
res = ''.join(re.findall('\d+',stringA))
# printing resultant string
print("Numeric Pefix from the string: \n", res)输出
运行以上代码将得到以下结果:
Given string : 347Hello Numeric Pefix from the string: 347
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP