473,411 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,411 software developers and data experts.

how to improve this simple block of code

py
Say I have...
x = "132.00"

but I'd like to display it to be "132" ...dropping the trailing
zeros...I currently try this

if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("."):
x = x[:len(x)-1]

I do it like this because if
x = "132.15" ...i dont want to modify it. But if
x = "132.60" ...I want it to become "132.6"

is there a better way to do this? It seems a bit ugly to me.

T.I.A
(thanks in advance)

Jan 11 '06 #1
17 1156
py wrote:
Say I have...
x = "132.00"

but I'd like to display it to be "132" ...dropping the trailing
zeros...I currently try this

if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("0"):
x = x[:len(x)-1]
if x.endswith("."):
x = x[:len(x)-1]

I do it like this because if
x = "132.15" ...i dont want to modify it. But if
x = "132.60" ...I want it to become "132.6"

is there a better way to do this? It seems a bit ugly to me.

T.I.A
(thanks in advance)


x = x.rstrip('0') # removes trailing zeros
x = x.rstrip('.') # removes trailing dot(s)
Jan 11 '06 #2
Or combined:

x = x.rstrip('0.') # removes trailing zeroes and dots

Jan 11 '06 #3
hanz wrote:
Or combined:

x = x.rstrip('0.') # removes trailing zeroes and dots

"130.00".rstrip("0.")

'13'

Oops.

Peter
Jan 11 '06 #4
py
hanz wrote:
x = x.rstrip('0.') # removes trailing zeroes and dots


knew there had to be a way, thanks.

Jan 11 '06 #5
In article <11**********************@f14g2000cwb.googlegroups .com>,
"py" <co*******@gmail.com> wrote:
Say I have...
x = "132.00"

but I'd like to display it to be "132" ...dropping the trailing
zeros...I currently try this

This sounds to me like a job for regular expressions. Something like:

re.sub (r'\.?0*$', '', x)

will do what you want. Check out the re module in the docs for more
details.
Jan 11 '06 #6
On Wed, 11 Jan 2006 13:58:05 -0000, py <co*******@gmail.com> wrote:
Say I have...
x = "132.00"

but I'd like to display it to be "132" ...dropping the trailing
zeros...


How about:

if "." in x:
x, frac = x.split(".")
frac = frac.rstrip("0")
if frac:
x = x + "." + frac
Copes if x = "132" too. If there'll always be a decimal point, then you
can leave off the initial "if".

Matt
--

| Matt Hammond
| R&D Engineer, BBC Research & Development, Tadworth, Surrey, UK.
| http://kamaelia.sf.net/
| http://www.bbc.co.uk/rd/
Jan 11 '06 #7
"py" <co*******@gmail.com> writes:
Say I have...
x = "132.00"
but I'd like to display it to be "132" ...dropping the trailing
zeros...I currently try this
The two-strip solution is cleaner, but:
if x.endswith("0"):
x = x[:len(x)-1]

x = x[:-1]
or
del x[-1]

both improve that one statement.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jan 11 '06 #8
Mike Meyer wrote:
"py" <co*******@gmail.com> writes:
Say I have...
x = "132.00"
but I'd like to display it to be "132" ...dropping the trailing
zeros...I currently try this


The two-strip solution is cleaner, but:
if x.endswith("0"):
x = x[:len(x)-1]

x = x[:-1]
or
del x[-1]

both improve that one statement.

del "it's tempting not to try"[-1]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item deletion

Just-pointing-out-what-does-not-work-ly yours

Peter
Jan 11 '06 #9
py wrote:
x = "132.15" ...i dont want to modify it. But if
x = "132.60" ...I want it to become "132.6"

is there a better way to do this? It seems a bit ugly to me.


The following works as long as you don't mind losing leading zeros
as well:

x = x.strip('0')

Gary Duzan
Motorola CHS
Jan 11 '06 #10
> How about:

if "." in x:
x, frac = x.split(".")
frac = frac.rstrip("0")
if frac:
x = x + "." + frac


Or simpler still:

if "." in x:
x = x.rstrip("0")
x = x.rstrip(".")
More concise, but slightly less readable IMO:

if "." in x:
x = x.rstrip("0").rstrip(".")

--

| Matt Hammond
| R&D Engineer, BBC Research & Development, Tadworth, Surrey, UK.
| http://kamaelia.sf.net/
| http://www.bbc.co.uk/rd/
Jan 11 '06 #11
py wrote:
hanz wrote:
x = x.rstrip('0.') # removes trailing zeroes and dots


knew there had to be a way, thanks.


But that's not it. :-)

This is a wonderful opportunity for you to learn about unit testing, and
begin the long process of developing good testing habits. Of all the
ideas posted, I believe only Mark Hammond's would correctly pass the
basic obvious test cases, and I don't think anyone (without actually
having checked with tests) should be saying even his is clearly correct.

import unittest
from yourmodule import stripZeros # or whatever you have

class Tests(unittest.TestCase):
def test01(self):
'check zero-stripper'
for input, expected in [
('', ''),
('0', '0'),
('0.0', '0'),
('0.', '0'),
('000.', '000'),
('10', '10'),
('10.0', '10'),
('foo', 'foo'),
('foo.', 'foo'), # ??
('132.15', '132.15'),
('132.60', '132.6'),
('132.00', '132'),
('132.00000', '132'),
('132.000001', '132.000001'),
# add others to taste
]:
self.assertEquals(expected, stripZeros(input))

unittest.main()
Change the above test cases to match what you really want if they're not
correct, then run the script and make sure everything passes.

-Peter

Jan 11 '06 #12
Peter Hansen wrote:
Of*all*the ideas posted, I believe only Mark Hammond's would correctly
pass the basic obvious test cases


Too bad he didn't post at all :-)

Peter

Jan 11 '06 #13
Peter Otten wrote:
Peter Hansen wrote:
Of all the ideas posted, I believe only Mark Hammond's would correctly
pass the basic obvious test cases


Too bad he didn't post at all :-)


D'oh! There was a typo in my message above. Naturally, I meant to
write "M. Hammond" instead of "Mark Hammond". ;-)

Sorry Matt!

-Peter

Jan 11 '06 #14
py wrote:
Say I have...
x = "132.00"

but I'd like to display it to be "132" ...dropping the trailing
zeros...


print '%g' % (float(x),)

might work.

Mel.

Jan 11 '06 #15
Mel Wilson wrote:
py wrote:
Say I have...
x = "132.00"

but I'd like to display it to be "132" ...dropping the trailing
zeros...


print '%g' % (float(x),)

might work.

Mel.

The input is a string, %g expects a float, TypeError exception.
Jan 11 '06 #16
Forget about the previous mail, i just saw you were converting the
string to float beforehand, in which case he would more than likely run
into the good ol' float imprecision issue sooner than later.

Not to mention that %g formats to scientific notation (e.g. exponential
format with the exponent always being a multiple of 3), he'd probably
use "%f".
Jan 11 '06 #17
On Wed, 11 Jan 2006 05:58:05 -0800, py wrote:
Say I have...
x = "132.00"

but I'd like to display it to be "132" ...dropping the trailing
zeros...I currently try this
Mucking about with the string is one solution. Here is another:

print int(float(x))

I do it like this because if
x = "132.15" ...i dont want to modify it. But if
x = "132.60" ...I want it to become "132.6"


Then you want:

x = float("123.60") # full precision floating point value
r = round(x, 1) # rounded to one decimal place

--
Steven.

Jan 14 '06 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
by: Brian Sabbey | last post by:
Here is a first draft of a PEP for thunks. Please let me know what you think. If there is a positive response, I will create a real PEP. I made a patch that implements thunks as described here....
3
by: querypk | last post by:
What is the fastest way to code this particular block of code below.. I used numeric for this currently and I thought it should be really fast.. But, for large sets of data (bx and vbox) it takes...
8
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value...
7
by: dphizler | last post by:
This is the basic concept of my code: #include <iostream.h> #include <math.h> #include <stdlib.h> int main() { double Gtotal, L, size, distance, theRandom; double Gi; int xi, xf, yi, yf,...
14
by: dba_222 | last post by:
Dear experts, Again, sorry to bother you again with such a seemingly dumb question, but I'm having some really mysterious results here. ie. Create procedure the_test As
5
by: Mike | last post by:
Hello All, Please, if anyone can point me to the problem, I'd sure appreciate it! I am very new to VB programming and not a programmer to begin with. This is part of a Visual Basic 2005 Express...
11
by: Peted | last post by:
Im using c# 2005 express edition Ive pretty much finished an winforms application and i need to significantly improve the visual appeal of the interface. Im totaly stuck on this and cant seem...
2
by: stevemtno | last post by:
I've got a problem with a web page I'm working on. I have 4 modules - one of them has 2 tabs, two of them have 4 tabs. When the user clicks on the tabs, the content below them changes. However, when...
2
by: sdanda | last post by:
Hi , Do you have any idea how to improve my java class performance while selecting and inserting data into DB using JDBC Connectivity ......... This has to work for more than 8,00,000...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.