python分离数字和符号,Python正则表达式将字符串拆分为数字和文本/符号

I would like to split a string into sections of numbers and sections of text/symbols

my current code doesn't include negative numbers or decimals, and behaves weirdly, adding an empty list element on the end of the output

import re

mystring = 'AD%5(6ag 0.33--9.5'

newlist = re.split('([0-9]+)', mystring)

print (newlist)

current output:

['AD%', '5', '(', '6', 'ag ', '0', '.', '33', '--', '9', '.', '5', '']

desired output:

['AD%', '5', '(', '6', 'ag ', '0.33', '-', '-9.5']

解决方案

Your issue is related to the fact that your regex captures one or more digits and adds them to the resulting list and digits are used as a delimiter, the parts before and after are considered. So if there are digits at the end, the split results in the empty string at the end to be added to the resulting list.

You may split with a regex that matches float or integer numbers with an optional minus sign and then remove empty values:

result = re.split(r'(-?\d*\.?\d+)', s)

result = filter(None, result)

To match negative/positive numbers with exponents, use

r'([+-]?\d*\.?\d+(?:[eE][-+]?\d+)?)'

The -?\d*\.?\d+ regex matches:

-? - an optional minus

\d* - 0+ digits

\.? - an optional literal dot

\d+ - one or more digits.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值