python 从字符串中提取数字并求和

从字符串中提取数字

如从"i13love14you520"中提取出来 13,14,520,然后相加求和
方法1:

s = "i13love14you520"
new_str = ""  		#创建一个空字符串
for ch in s:
	if ch.isdigit():		#字符串中的方法,可以直接判断ch是否是数字
		new_str += ch
	else:
		new_str += " "
sub_list = new_str.split()   #对新的字符串切片
num_list = list(map(int, sub_list)) 	#map方法,使列表中的元素按照指定方式转变
res  =sum(num_list)
print(res)

方法2:

s = "i13love14you520"
new_str = ""  		#创建一个空字符串
for ch in s:
	if ch.isdigit():		#字符串中的方法,可以直接判断ch是否是数字
		new_str += ch
	else:
		new_str += " "
sub_list = new_str.split()
print(sub_list)
ex_str = "+".join(sub_list)	#使用join()方法拼接字符串
print(eval(ex_str))

方法3:利用正则表达式,导入模块re

import re
re_obj = re.compile(r"\d+")		#创建正则表达式对象
res_list = re_obj.findall(s)		#利用findall将找的的符合要求的放入列表中
num_list = list(map(int, res_list))		#map方法,使列表中的元素按照指定方式转变
print(sum(num_list))
  • 15
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值