[Tutor] Accessing a tuple of a dictionary's value

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 24 05:02:13 EDT 2018


CCing list, please always use Reply-All or Reply-List when responding
to the tutor list so that everyone gets a chance to reply.


On 24/08/18 00:35, Roger Lea Scherer wrote:
>
> Lots of code missing, but the line I'm interested in is this:
> print("Your number  " + str(numerator) + "/" + str(denominator) + " 
> is approximately  " + str(fractions[ranges[i][0]][0]) + "/" +
> str(fractions[ranges[i][0]][1]))
> I get this output:
> Your number  37/112  is approximately  1/3
>
> From this line:
> print("Your number ",  numerator, "/",  denominator, " is
> approximately ", fractions[ranges[i][0]][0], "/",
> fractions[ranges[i][0]][1])
> I get this output:
> Your number  37 / 112  is approximately  1 / 3
>
> I'm being picky. I don't like the spaces between the 37 and 112 and 1
> and 3...

> my question is: Is there another way other than these two to
> print without all the str nonsense and not get the spaces

Yes, use string formatting. It gives you much more control over the
content of your string including field width, number of decimal places,
justification, etc.

For example in your case:


print("Your number  %d/%d is approximately %d/%d" % (numerator,
                                                     denominator,
                                                    
fractions[ranges[i][0]][0],
                                                    
fractions[ranges[i][0]][1]))

The stacked layout is of course optional, I just think it looks clearer.

See the thread on TimesTable for more on formatting and look at
the documentation :

https://docs.python.org/3/library/stdtypes.html#old-string-formatting
and
https://docs.python.org/3/library/string.html#formatstrings

Use whichever style you prefer.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list