Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #87379
| Date | 2015-03-13 12:38 -0500 |
|---|---|
| From | Tim Chase <python.list@tim.thechases.com> |
| Subject | Re: regex help |
| References | <CACwCsY6cN6+mZVYWnMpKGsXg6jd7Y8Gav9DC7HkXcPtU-pDXDw@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.334.1426268765.21433.python-list@python.org> (permalink) |
On 2015-03-13 12:05, Larry Martell wrote:
> I need to remove all trailing zeros to the right of the decimal
> point, but leave one zero if it's whole number.
>
> But I can't figure out how to get the 5.0000000000000000 to be 5.0.
> I've been messing with the negative lookbehind, but I haven't found
> one that works for this.
You can do it with string-ops, or you can resort to regexp.
Personally, I like the clarity of the string-ops version, but use
what suits you.
-tkc
import re
input = [
'14S',
'5.0000000000000000',
'4.56862745000000',
'3.7272727272727271',
'3.3947368421052630',
'5.7307692307692308',
'5.7547169811320753',
'4.9423076923076925',
'5.7884615384615383',
'5.137254901960000',
]
output = [
'14S',
'5.0',
'4.56862745',
'3.7272727272727271',
'3.394736842105263',
'5.7307692307692308',
'5.7547169811320753',
'4.9423076923076925',
'5.7884615384615383',
'5.13725490196',
]
def fn1(s):
if '.' in s:
s = s.rstrip('0')
if s.endswith('.'):
s += '0'
return s
def fn2(s):
return re.sub(r'(\.\d+?)0+$', r'\1', s)
for fn in (fn1, fn2):
for i, o in zip(input, output):
v = fn(i)
print "%s: %s -> %s [%s]" % (v == o, i, v, o)
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: regex help Tim Chase <python.list@tim.thechases.com> - 2015-03-13 12:38 -0500
csiph-web