我有一系列字符串,它们是两个数字:
1.782-100.799
-18.107-102.016
-17.504104.059
如何在每个字符串中第一个数字的第3个小数位后分割我的字符串?所以它看起来如下:
1.782 -100.799
-18.107 -102.016
-17.504 104.059
答案 0 :(得分:4)
使用正则表达式的启发式方法:
>>> import re
>>> s = """1.782-100.799
... -18.107-102.016
... -17.504104.059"""
>>> re.findall('-?\d{1,3}(?:\.\d{3})*', s)
['1.782', '-100.799', '-18.107', '-102.016', '-17.504', '104.059']
或者逐行进行以获得对:
>>> [re.findall('-?\d{1,3}(?:\.\d{3})*', ln) for ln in s.split("\n")]
[['1.782', '-100.799'], ['-18.107', '-102.016'], ['-17.504', '104.059']]
答案 1 :(得分:3)
这是一个不使用正则表达式的结果,以防你发现更好:
s = '1.782-100.799\n-18.107-102.016\n-17.504104.059'
result = []
for line in s.split('\n'):
i = line.index('.') + 4
result.append(line[:i] + ' ' + line[i:])
>>> print '\n'.join(result)
1.782 -100.799
-18.107 -102.016
-17.504 104.059
答案 2 :(得分:1)
真正基本的方法:
>>> data = """1.782-100.799
... -18.107-102.016
... -17.504104.059"""
>>> [(x[:x.find('.') + 4], x[x.find('.') + 4:]) for x in data.splitlines()]
[('1.782', '-100.799'), ('-18.107', '-102.016'), ('-17.504', '104.059')]
答案 3 :(得分:0)
import re
line = your_numbers_in_Strings_here
result = re.findall('-?\d*\.\d{3}',line)
newline = ' '.join(result)
The meaning of the regular expression (re):
? : preceding char zero or one time
* : preceding char zero or infinite times
\ : don't interprete the following char as an expression (escape)
{n}: preceding char exactly n-times
\d : decimal numbers 0-9
so:
'-?\d*\.\d{3}'
'-? ' = zero or 1 '-'
' \d*\. ' = zero or as many decimals before an '.'
' \d{3}' = exactly 3 decimals