Python Math: Display the fraction instances of the string representation of a number
43. Fraction from String Representation
Write a Python program to display fraction instances of the string representation of a number.
Sample Solution:
Python Code:
import fractions
for s in ['0.7', '2.5', '9.32', '7e-1']:
f = fractions.Fraction(s)
print('{0:>4} = {1}'.format(s, f))
Sample Output:
0.7 = 7/10 2.5 = 5/2 9.32 = 233/25 7e-1 = 7/10
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to convert a string representation of a decimal (e.g., '2.5') into a Fraction instance and print it.
- Write a Python function that accepts a list of numeric strings and returns a list of Fraction objects representing each number.
- Write a Python script to parse a CSV line of numeric strings, convert each to a Fraction, and then print the list of fractions.
- Write a Python program to read multiple numeric strings from input, convert them to Fraction instances, and display each fraction in its simplest form.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to get the local and default precision.
Next: Write a Python program to create the fraction instances of float numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.