[英]how to split string between different separators in python
我想從<personne01166+30-90>
提取一個子字符串,輸出應如下所示: +30
和-90
。
字符串可以是: 'personne01144+0-30'
、 'personne01146+0+0'
、 'personne01180+60-75'
等。
我試過用
<string.split('+')[len(string.split('+')) -1 ].split('+')[0]>
但輸出必須是兩個對應的數字。
以下是使用列表re.findall
和re.findall
:
import re
s = ['personne01144+0-30', 'personne01146+0+0', 'personne01180+60-75']
print([re.findall('[+-]\d+', i) for i in s])
輸出:
[['+0', '-30'], ['+0', '+0'], ['+60', '-75']]
re.findall('[+-]\\d+', i)
在字符串i
找到所有'[+-]\\d+'
的模式。
[+-]
表示任何+
或-
。 \\d+
表示一行中的所有數字。
如果你知道有趣的部分總是在+
之后,那么你可以簡單地拆分兩次。
numbers = string.split('+', 1)[1]
if '+' in numbers:
this, that = numbers.split('+')
elif '-' in numbers:
this, that = numbers.split('-')
that = -that
else:
raise ValueError('Could not parse %s', string)
不過,也許基於正則表達式的方法更有意義;
import re
m = re.search(r'([-+]\d+)([-+]\d+)$', string)
if m:
this, that = m.groups()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.