[Tutor] How to extract numerator and denominator from fractions.Fraction(4, 32)?

Amit Saha amitsaha.in at gmail.com
Mon Aug 5 17:49:25 CEST 2013


On Tue, Aug 6, 2013 at 12:34 AM, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Mon, Aug 5, 2013 at 6:15 AM, Amit Saha <amitsaha.in at gmail.com> wrote:
>> On Mon, Aug 5, 2013 at 10:51 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>>>>>> import fractions
>>>>>> fractions.Fraction(6, 21)
>>> Fraction(2, 7)
>>>
>>> How do I turn that Fraction(2, 7) into "1/7"? (and not 0.2857142857142857...)
>>
>> I think you meant, 2/7?
>
> Yes, sorry for screwing that up.
>
>  Here is how you can extract the numerator and
>> the denominator (as your subject states):
>>
>>>>> fractions.Fraction(6,21)
>> Fraction(2, 7)
>>>>> f=fractions.Fraction(6,21)
>>>>> f
>> Fraction(2, 7)
>>
>>>>> f.numerator
>> 2
>>>>> f.denominator
>> 7
>
> Ah, better yet! Thanks! But where could I have found that in
> <http://docs.python.org/3/library/fractions.html#module-fractions>?

Sometimes, you may also want to do dir() on an object to see what
attributes/methods it has/supports.



-- 
http://echorand.me


More information about the Tutor mailing list