I'm resending this to the list. Please reply to the tutor list rather
than directly to me. Also please don't top-post. My answer is below.

On 11 September 2013 10:47, Thabile Rampa <thabilera...@gmail.com> wrote:
>
> On Tue, Sep 10, 2013 at 11:57 AM, Oscar Benjamin <oscar.j.benja...@gmail.com> 
> wrote:
>>
>> On 10 September 2013 08:58, Thabile Rampa <thabilera...@gmail.com> wrote:
>> > On Aug 27, 2013, at 3:40 AM, isaac Eric wrote
>> >
>> > According to my understanding, the purpose of the %s is to turn the 
>> > numbers,
>> > which the program has recognized as numbers, into strings, so that they fit
>> > in the print command without any syntax errors.
>> >
>>
>> You are correct. '%s' is used to convert numbers (or other non-string
>> things) into strings so that they can be used in places where text is
>> required. In the particular case of the print command, this is done
>> automatically so printing a number directly works just fine:
>>
> Wow! Thanks so much guy!
>
> The last two paragraphs especially made it a lot easier to understand! but 
> why are there so many ways to achieve one goal in Python?

The str() function is the default way to convert an object to a
string. The print statement uses this implicitly if you try to print
something that is not a string which is convenient for simple output.
The % formatting codes allow for more advanced usage (see below) but
%s is just for the specific case where you want to convert each object
using str(). Here's how you can use % formatting to represent the same
number in different ways:

>>> radius = 12.3456789
>>> radius
12.3456789
>>> print 'radius =', radius
radius = 12.3456789
>>> print 'radius = %s' % radius
radius = 12.3456789
>>> print 'radius = %.3f' % radius
radius = 12.346
>>> print 'radius = %.5f' % radius
radius = 12.34568
>>> print 'radius = %.5e' % radius
radius = 1.23457e+01

There is also the .format method. This was initially intended to
replace % formatting but it was ultimately decided that removing %
formatting was not necessary. Consequently there are now two ways of
doing advanced string formatting in Python.


Oscar
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to