Python3中字符串中的数字提取方法
Python3中字符串中的数字提取方法
>>> totalCount = '100abc'
>>> totalCount = re.sub("\D", "", totalCount)
>>> print(totalCount)
100
>>> type(totalCount)
<class 'str'>
在Python3.5.2 官方文档re模块中sub函数的定义是:
re.sub(pattern, repl, string, count=0, flags=0)
在字符串 string 中找到匹配正则表达式 pattern 的所有子串,用另一个字符串 repl 进行替换。如果没有找到匹配 pattern 的串,则返回未被修改的 string。Repl 既可以是字符串也可以是一个函数。
由此可分析上面使用的语句的含义:在'100abc'这个字符串中找到非数字的字符(正则表达式中'\D'表示非数字),并用""替换,然后返回的就是只剩下数字的字符串。
========================================================
python根据开头和结尾字符串获取中间字符串的方法:
这里给定一个字符串,指定开头和结尾的字符串,返回中间包夹的字符串,比如:
content:<div class="a">jb51.net</div>
startStr:<div class="a">
endStr:</div>
返回结果:jb51.net
def get_middle_str(content,start_str,end_str):
start_index = content.index(start_str)
if start_index>=0:
start_index += len(start_str)
end_index = content.index(end_str)
return content[start_index:end_index]
方法二:re正则表达式
正则表达式:
>.+.<
(开头字符串.+.结尾字符串)
pattern= re.compile(r">(.*?)< ")
result1 = re.findall(pattern,content)
正则表达式判断以字母开头的
pattern = re.compile("^[0-9a-zA-z].*")

浙公网安备 33010602011771号