Reputation: 12587
I have a series of strings, which are two numbers:
1.782-100.799
-18.107-102.016
-17.504104.059
How do I split my string after the 3rd decimal place of the first number in each string? so it looks as follows:
1.782 -100.799
-18.107 -102.016
-17.504 104.059
Upvotes: 1
Views: 376
Reputation: 11614
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
Upvotes: 0
Reputation: 208495
Here is a result that doesn't use regular expressions, in case you find that preferable:
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
Upvotes: 3
Reputation: 10585
Really basic approach:
>>> 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')]
Upvotes: 1
Reputation: 363627
Heuristic approach using regular expressions:
>>> 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']
Or do this line-by-line to get pairs:
>>> [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']]
Upvotes: 4