简体   繁体   中英

Python: split float after 3rd decimal place

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

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']]

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

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')]
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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM