473,801 Members | 2,361 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Elementary string-formatting

Hello, group: I've just begun some introductory tutorials in Python.
Taking off from the "word play" exercise at

<http://www.greenteapre ss.com/thinkpython/html/book010.html#to c96>

I've written a mini-program to tabulate the number of characters in each
word in a file. Once the data have been collected in a list, the output
is produced by a while loop that steps through it by incrementing an
index "i", saying

print '%2u %6u %4.2f' % \
(i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0])

My problem is with the last entry in each line, which isn't getting
padded:

1 0 0.00
2 85 0.07
3 908 0.80
4 3686 3.24
5 8258 7.26
6 14374 12.63
7 21727 19.09
8 26447 23.24
9 16658 14.64
10 9199 8.08
11 5296 4.65
12 3166 2.78
13 1960 1.72
14 1023 0.90
15 557 0.49
16 261 0.23
17 132 0.12
18 48 0.04
19 16 0.01
20 5 0.00
21 3 0.00

I've tried varying the number before the decimal in the formatting
string; "F", "g", and "G" conversions instead of "f"; and a couple of
other permutations (including replacing the arithmetical expression in
the tuple with a variable, defined on the previous line), but I can't
seem to get the decimal points to line up. I'm sure I'm missing
something obvious, but I'd appreciate a tip -- thanks in advance!

FWIW I'm running

Python 2.3.5 (#1, Oct 5 2005, 11:07:27)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

from the Terminal on Mac OS X v10.4.11.

P.S. Is there a preferable technique for forcing floating-point division
of two integers to that used above, multiplying by "100.0" first? What
about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n /
m"?

--
Odysseus
Jan 13 '08 #1
9 1525
Odysseus wrote:
Hello, group: I've just begun some introductory tutorials in Python.
Taking off from the "word play" exercise at

<http://www.greenteapre ss.com/thinkpython/html/book010.html#to c96>

I've written a mini-program to tabulate the number of characters in each
word in a file. Once the data have been collected in a list, the output
is produced by a while loop that steps through it by incrementing an
index "i", saying

print '%2u %6u %4.2f' % \
(i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0])
Using 4.2 is the problem. The first digit (your 4) give the total
number of characters to use for the number. Your numbers require at
least 5 characters, two digits, one decimal point, and two more
digits. So try 5.2, or 6.2 or 7.2 or higher if your numbers can grow
into the hundreds or thousands or higher. If you want to try one of the
floating point formats, then your first number must be large enough to
account for digits (before and after) the decimal point, the 'E', and
any digits in the exponent, as well as signs for both the number and the
exponent.

Gary Herron
My problem is with the last entry in each line, which isn't getting
padded:

1 0 0.00
2 85 0.07
3 908 0.80
4 3686 3.24
5 8258 7.26
6 14374 12.63
7 21727 19.09
8 26447 23.24
9 16658 14.64
10 9199 8.08
11 5296 4.65
12 3166 2.78
13 1960 1.72
14 1023 0.90
15 557 0.49
16 261 0.23
17 132 0.12
18 48 0.04
19 16 0.01
20 5 0.00
21 3 0.00

I've tried varying the number before the decimal in the formatting
string; "F", "g", and "G" conversions instead of "f"; and a couple of
other permutations (including replacing the arithmetical expression in
the tuple with a variable, defined on the previous line), but I can't
seem to get the decimal points to line up. I'm sure I'm missing
something obvious, but I'd appreciate a tip -- thanks in advance!

FWIW I'm running

Python 2.3.5 (#1, Oct 5 2005, 11:07:27)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

from the Terminal on Mac OS X v10.4.11.

P.S. Is there a preferable technique for forcing floating-point division
of two integers to that used above, multiplying by "100.0" first? What
about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n /
m"?

Jan 13 '08 #2
On Jan 13, 3:15 pm, Odysseus <odysseus1479.. .@yahoo-dot.cawrote:
[snip]
>
P.S. Is there a preferable technique for forcing floating-point division
of two integers to that used above, multiplying by "100.0" first? What
about if I just wanted a ratio: is "float(n / m)" better than "1.0 * n /
m"?
Odysseus
You obviously haven't tried float(n / m), or you wouldn't be asking.
Go ahead and try it.

"Preferable " depends on whether you want legibility or speed.

Most legible and slowest first:
1. float(n) / float(m)
2. n / float(m)
3. 1.0 * n / m
# Rationale so far: function calls are slow
4. If you have a lot of this to do, and you really care about the
speed and m (the denominator) is constant throughout, do fm = float(m)
once, and then in your loop do n / fm for each n -- and make sure you
run properly constructed benchmarks ...

Recommendation: go with (2) until you find you've got a program with
a real speed problem (and then it probably won't be caused by this
choice).

HTH,
John
Jan 13 '08 #3
On Jan 12, 10:15 pm, Odysseus <odysseus1479.. .@yahoo-dot.cawrote:
P.S. Is there a preferable technique for forcing floating-point division
of two integers to that used above, multiplying by "100.0" first?
Put this at the beginning of your program:

from __future__ import division

This forces all divisions to yield floating points values:
>>1/3
0
>>from __future__ import division
1/3
0.3333333333333 3331
>>>
HTH,
--
Roberto Bonvallet
Jan 13 '08 #4
In article
<a2************ *************** *******@d4g2000 prg.googlegroup s.com>,
John Machin <sj******@lexic on.netwrote:

<snip>
>
You obviously haven't tried float(n / m), or you wouldn't be asking.
True, it was a very silly idea.
Most legible and slowest first:
1. float(n) / float(m)
2. n / float(m)
3. 1.0 * n / m
Recommendation: go with (2) until you find you've got a program with
a real speed problem (and then it probably won't be caused by this
choice).
I had actually used n / float(m) at one point; somehow the above struck
me as an improvement while I was writing the message. Thanks for the
reality check.

--
Odysseus
Jan 13 '08 #5
In article
<e6************ *************** *******@v46g200 0hsv.googlegrou ps.com>,
Roberto Bonvallet <rb******@gmail .comwrote:
Put this at the beginning of your program:

from __future__ import division

This forces all divisions to yield floating points values:
Thanks for the tip. May I assume the div operator will still behave as
usual?

--
Odysseus
Jan 13 '08 #6
On Jan 13, 8:43 pm, Odysseus <odysseus1479.. .@yahoo-dot.cawrote:
In article
<e6f9c0c3-d248-46ae-af0f-fbb8ab279...@v4 6g2000hsv.googl egroups.com>,
Roberto Bonvallet <rbonv...@gmail .comwrote:
Put this at the beginning of your program:
from __future__ import division
This forces all divisions to yield floating points values:

Thanks for the tip. May I assume the div operator will still behave as
usual?
div operator? The integer division operator is //
>>from __future__ import division
1 / 3
0.3333333333333 3331
>>1 // 3
0
>>22 / 7
3.1428571428571 428
>>22 // 7
3
>>22 div 7
File "<stdin>", line 1
22 div 7
^
SyntaxError: invalid syntax
>>>
Jan 13 '08 #7
In article <ma************ *************** *********@pytho n.org>,
Gary Herron <gh*****@island training.comwro te:
Odysseus wrote:
<snip>

print '%2u %6u %4.2f' % \
(i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0])
Using 4.2 is the problem. The first digit (your 4) give the total
number of characters to use for the number.
Thanks; I was thinking the numbers referred to digits before and after
the decimal. The largest figures have five characters in all, so they
were 'overflowing'.

--
Odysseus
Jan 13 '08 #8
Odysseus wrote:
Hello, group: I've just begun some introductory tutorials in Python.
Taking off from the "word play" exercise at

<http://www.greenteapre ss.com/thinkpython/html/book010.html#to c96>

I've written a mini-program to tabulate the number of characters in each
word in a file. Once the data have been collected in a list, the output
is produced by a while loop that steps through it by incrementing an
index "i", saying

print '%2u %6u %4.2f' % \
(i, wordcounts[i], 100.0 * wordcounts[i] / wordcounts[0])
This isn't very important, but instead of keeping track of the index
yourself, you can use enumerate():
>>mylist = ['a', 'b', 'c']
for i, item in enumerate(mylis t):
.... print i, item
....
0 a
1 b
2 c
>>>
Err, it doesn't look like you can make it start at 1 though.

<snip>
--
Jan 13 '08 #9
In article
<7d************ *************** *******@q77g200 0hsh.googlegrou ps.com>,
John Machin <sj******@lexic on.netwrote:

<snip>
>
div operator? The integer division operator is //
Yes, sorry, that's what I meant.

--
Odysseus
Jan 14 '08 #10

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

Similar topics

5
1408
by: Last Timer | last post by:
I encountered the following code in Bruce Eckel's online book. Can you please clarify what "const char* const data;" means? Thanks //: C01:MyError.cpp {RunByHand} class MyError { const char* const data; public: MyError(const char* const msg = 0) : data(msg) {} };
5
2849
by: Lionel B | last post by:
Greetings, I am trying to implement "element-wise" arithmetic operators for a class along the following lines (this is a simplified example): // ----- BEGIN CODE ----- struct X { int a,b;
29
1883
by: Merrill & Michele | last post by:
I'm now looking at page 115 K&R. After having discussed counterexamples, I shall herewith and henceforth make all my c programs look like int main(int orange, char* apple) {return(0);} Q1) How large is that int and that char*? (My instinct would be to look at limits.h, but with the main call, I can't figure out to what extent I'm %inside% C.)
20
1296
by: Merrill & Michele | last post by:
I am determining how best to call an already compiled c program from another. The following is a program that compiles and shows the information passed: //Text1.cpp #include <stdio.h> int main(int argc, char* argv) { int i;
0
2892
by: Geoffrey L. Collier | last post by:
I wrote a bunch of code to do elementary statistics in VB, and would prefer to find code in C# to recoding all of the VB code. A search of the web found very little. Does anyone know of a good set of classes to do these things, free, or for fee? Thanks, Geoff Collier
5
2535
by: bromio | last post by:
can someone help me to make code for digital clock using AT89S52. The specs of clock are 12 hour clock,am-pm display,use timer interrupts to have delay.two external inputs to adjust hours and minutes,use 4 digit hex display multiplexing.
11
1551
by: pauldepstein | last post by:
I am using the xlw package as a c++ wrapper for excel functions. In our c++ library, there is an excel function which our c++ developers refer to as DevelopersFunction, and which the excel users refer to as ExcelFunction. There is some code containing the string "DevelopersFunction" which results in the excel users seeing the text DevelopersFunction when they use the insert_function command in excel. But the excel users should see...
9
1241
by: [Mr.] Lynn Kurtz | last post by:
I'm new to javascript and I have run into a problem I bet someone here can help me with. I have a little web page that includes this call to another html file with two parameters: <a href="car.html?chevy.jpg|nameone"> <img src="slides/chevythumbnail.jpg" > </a> So when I click on the chevythumbnail image, it brings up the car.html page with the parameter string. I have figured out how read and parse
10
2021
by: Descartes | last post by:
Dear All, Coming from another development environment, it appears that I bang my head in the wall on very basic matters, so I hope you can give me a push in the right direction. The application that I work on will consist of - a mainform with a usual menu and toolbar and not much more. - a number of modal data editing forms with various edit controls, an OK button and a Cancel button
4
1879
by: tonywh00t | last post by:
Hi everyone, I have a "simple" question, especially for people familiar with regex. I need to parse strings that have the form: 1:3::5:9 which indicates the set of integers {1 3 4 5 9}. In other words i have a set of numbers separated by ":", where "::" indicates a range from lo to hi inclusive. It is desirable to error check this string (i.e it
0
9697
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9555
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
10291
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...
1
10260
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10049
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
9100
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7589
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4156
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
3
2956
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.