473,594 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simple string formatting question

I have a sinking feeling I'm missing something really,
really simple.

I'm looking for a format string similar to '%.3f'
except that trailing zeroes are not included.

To give some examples:

Float String
1.0 1
1.1 1.1
12.1234 12.123
12.0001 12

and similar.

Here is a (quick and dirty) reference implementation:

def format(f, width=3):
fs = '%%.%df' % width
s = fs % f
return s.rstrip('0').r strip('.')
Is there a way of getting the same result with just a
single string format expression?

--
Steven

Apr 6 '06 #1
7 1684
"Steven D'Aprano" <st***@REMOVEME cyber.com.au> writes:
I have a sinking feeling I'm missing something really, really
simple.
"Oh no, everyone in the galaxy gets that, that's perfectly natural
paranoia."
I'm looking for a format string similar to '%.3f' except that
trailing zeroes are not included.


Can;t be done, to my knowledge. You specify a particular precision,
and the number will be formatted at that precision. This matches the
'printf' behaviour that inspired string formatting operations.

If your brute-force approach works, stick to that until you have a
reason to look for something better.

--
\ "I have an answering machine in my car. It says, 'I'm home now. |
`\ But leave a message and I'll call when I'm out.'" -- Steven |
_o__) Wright |
Ben Finney

Apr 6 '06 #2
Steven D'Aprano wrote:
Here is a (quick and dirty) reference implementation:

def format(f, width=3):
fs = '%%.%df' % width
s = fs % f
return s.rstrip('0').r strip('.')

Is there a way of getting the same result with just a
single string format expression?


not with % itself, but you can do it all in one line:

def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )

</F>

Apr 6 '06 #3
"Fredrik Lundh" <fr*****@python ware.com> wrote in message
news:ma******** *************** *************** *@python.org...
Steven D'Aprano wrote:
Here is a (quick and dirty) reference implementation:

def format(f, width=3):
fs = '%%.%df' % width
s = fs % f
return s.rstrip('0').r strip('.')

Is there a way of getting the same result with just a
single string format expression?


not with % itself, but you can do it all in one line:

def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )

</F>

Ooops, don't combine the two calls to rstrip().

def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )

print format(3.140)
print format(3.000)
print format(3.000000 1)
print format(30.0000)
print format(300000.0 00)

Gives:
3.14
3
3
3
3

But this works fine:
def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0") .rstrip(".")
-- Paul


Apr 6 '06 #4
On Thu, 06 Apr 2006 22:16:05 +1000, Ben Finney wrote:
"Steven D'Aprano" <st***@REMOVEME cyber.com.au> writes:

I'm looking for a format string similar to '%.3f' except that
trailing zeroes are not included.


Can;t be done, to my knowledge. You specify a particular precision,
and the number will be formatted at that precision. This matches the
'printf' behaviour that inspired string formatting operations.

If your brute-force approach works, stick to that until you have a
reason to look for something better.


Thanks to everybody who replied, I'm glad to see I didn't miss anything.

I do actually have a reason for wanting a single format pattern, but I can
probably work with what I have, it will just be less convenient.

I hesitate to suggest this, what with the whole PEP procedure and all
being so intimidating to those who aren't familiar with it (e.g. me), but
would there be any interest in extending the formatting operations to
include such a feature? It would (presumably) break compatibility with
printf, but does that matter?

--
Steven.

Apr 6 '06 #5
"Steven D'Aprano" <st***@REMOVETH IScyber.com.au> writes:
On Thu, 06 Apr 2006 22:16:05 +1000, Ben Finney wrote:
"Steven D'Aprano" <st***@REMOVEME cyber.com.au> writes: 1> >> I'm looking for a format string similar to '%.3f' except that
trailing zeroes are not included.


Can;t be done, to my knowledge. You specify a particular
precision, and the number will be formatted at that
precision. This matches the 'printf' behaviour that inspired
string formatting operations.


[...] would there be any interest in extending the formatting
operations to include such a feature? It would (presumably) break
compatibility with printf, but does that matter?


-1 from me. The concept of "precision" is fairly well defined; you're
talking about combining that with something more special-case. In
general, "special cases aren't special enough to break the rules", and
the programemr should be forced to spell out what he's doing so that
it's obvious.

In the specific cases of the string formatting codes, they're a
special case that is a marginal win because of the large body of
existing experience with the standard C printf codes. That's weighed
against their considerable lack of readability; expand them to be
special for Python, and that "marginal win" is gone.

--
\ "My girlfriend has a queen sized bed; I have a court jester |
`\ sized bed. It's red and green and has bells on it, and the ends |
_o__) curl up." -- Steven Wright |
Ben Finney

Apr 7 '06 #6
Paul McGuire wrote:
Ooops, don't combine the two calls to rstrip().

def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0" )

print format(3.140)
print format(3.000)
print format(3.000000 1)
print format(30.0000)
print format(300000.0 00)
hey, I'm doing test-driven development. being able to handle 30 and
300000 wasn't part of the original spec ;-)
But this works fine:
def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0") .rstrip(".")


indeed.

</F>

Apr 7 '06 #7
Steven D'Aprano wrote:
I have a sinking feeling I'm missing something really,
really simple.

I'm looking for a format string similar to '%.3f'
except that trailing zeroes are not included.

To give some examples:

Float String
1.0 1
1.1 1.1
12.1234 12.123
12.0001 12

and similar.

Here is a (quick and dirty) reference implementation:

def format(f, width=3):
fs = '%%.%df' % width
s = fs % f
return s.rstrip('0').r strip('.')
Is there a way of getting the same result with just a
single string format expression?


Does it have to be a string or can you cheat? If so:
class Format(str): .... def __new__(cls, width):
.... return str.__new__(cls , "%%.%df" % width)
.... def __mod__(self, other):
.... return str.__mod__(sel f, other).rstrip(" 0").rstrip(" .")
.... format = Format(3)
for f in [1.0, 1.1, 12.1234, 12.0001]:

.... print f, "-->", format % f
....
1.0 --> 1
1.1 --> 1.1
12.1234 --> 12.123
12.0001 --> 12

For passing around in your app that should be as convenient as a string --
of course it will break if you store the "format" in a file, say.

Peter
Apr 7 '06 #8

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

Similar topics

7
5479
by: Ot | last post by:
I posted this to the wrong group. It went to m.p.dotnet.languages.vb. Ooops. -------------------------------------------------------------------- I have this tiny problem. I have learned that an xpath expression can be bounded by either single or double quotation marks. But sometimes I want to search for a title containing both a single and double quote. Any way to do this?
8
3340
by: Tony | last post by:
Hello I am learning C# and encountered the following problem when I tried to figure out how to print the string {0} in a Console window The following piece of codes complied OK. But when I ran it, it failed The codes are using System class Test
3
1121
by: The Eeediot | last post by:
How do I get a number like "131" to appear in a currency format like "$131.00" in a TextBox control? I know it's simple but I cannot find how to do this in any reference manual. TIA....
5
1789
by: Burak | last post by:
Hello, I would like to format the string "11304200" into "11-3042.00". Can I do this with String.Format method? I have not come across any good documentation. Thank you,
6
1496
by: alexrussell101 | last post by:
For anyone who can't be bothered to read my code and examples, scroll to the bottom, the question's there. Thanks. I'm using php and regular expressions to convert bbcode style things to html. My code to convert something like this: Hello there
8
3540
by: rdrink | last post by:
I am just getting into pysqlite (with a fair amount of Python and MySQL experience behind me) and have coded a simple test case to try to get the hang of things... yet have run into a 'stock simple' problem... I can create a database 'test.db', add a table 'foo' (which BTW I repeatedly DROP on each run) with one INTGER column 'id', and can insert data into with: cur.execute("INSERT INTO foo (id) VALUES (200)") con.commit()
11
4989
by: Dustan | last post by:
Is there any builtin function or module with a function similar to my made-up, not-written deformat function as follows? I can't imagine it would be too easy to write, but possible... 'I am coding, and he coded last week.' ('coding', 'coded', 'week') expanded (for better visual): ('coding', 'coded', 'week')
2
1226
by: RichB | last post by:
I am attempting to output a trace with details of the db id of a price using: Trace.WriteLine("price id(first price): {0}",evnt.Prices.Id); Wher the Id is a string. I expect from this to output price id(first price): instead I get:
0
1118
by: opedog | last post by:
I'm monkeying around with databinding, trying to learn all the ins and outs. I'm populating a label from one of my business objects properties which is a string, however, I want some formatting done on the string first. I got this working using the binding's Format event. But, I want to go one step further. Instead of using the Format event, I'm trying to set the FormatString and FormatInfo properties to make the databinding go through the...
0
7880
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8255
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8374
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8242
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5413
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3868
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3903
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2389
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.