Python String Parsing Floats [duplicate] - python

This question already has answers here:
Convert fraction to float?
(9 answers)
Closed 8 years ago.
How to change a '14/15' string to a float?
I am trying to extract data from a text file would like to convert '1/3' to a float. float('1/3') doesn't work. I was thinking about splitting into two parts at '/' by 1 and 3 then dividing, but it seems cludgy. Is there a more pythonic way to do this? I'm using Python 2.7

If you only ever need to evaluate simple X/Y fractions:
s = "14/15"
num, denom = map(float, s.split("/", 1))
print(num / denom)
If you need a more complete expression evaluator, take a look at the asteval module.
Using eval() might also see like a nice easy way to do it, but I'd advise against it for security reasons.

If you trust your input:
from __future__ import division
eval('14/15')

Related

Very unusual fractions in Sympy, how do I solve this? [duplicate]

This question already has answers here:
How do I replace floats with rationals in a sympy expression?
(2 answers)
Closed 8 months ago.
I get very weird fractions in sympy.
I have no clue why it is given me these unusual fractions
To answer your question:
Rational("0.1")
# out: 1 / 10
Rational(0.1)
# out: 3602879701896397/36028797018963968
The second output happens because 0.1 is a number of type float, hence it is inherently inaccurate.
sympy manual: https://docs.sympy.org/latest/explanation/gotchas.html#python-numbers-vs-sympy-numbers
in short:
you type Rational(0.1), then sympy has to test a float.
but Rational("0.1") works. str keep the number.
if you don't like this.
First convert it to sympy's type Integer(1)/10. Also works.

Converting string to float with "," as thousands separator.. "123,000.12" to 123,000.12 [duplicate]

This question already has answers here:
Python Remove Comma In Dollar Amount
(4 answers)
Closed 2 years ago.
I can't perform any math operations on these values that I had exported. I'm using xlwt library to do this. Any way to convert these values in the format so that I can be able to perform math operations on it.
float('3629,473.237'.replace(',', ''))
You can replace the commas, they make no sense except readablity
n = float("3629,473.237".replace(",",""))
To re-add commas as string, you can use format strings:
print("{:,}".format(n))
There are f-strings in python 3.6+
print(f"{n:,}")
No; you'll have to remove the comma manually.
float("123,000.12".replace(',',''))
If you have consistent data, you might as well remove all the commas and convert the result.

How to run calculations [duplicate]

This question already has answers here:
How do I do exponentiation in python? [duplicate]
(3 answers)
Closed 2 years ago.
I am new to programming and just started a course and stuck on a demo section where I have to take a math calculation and program it in Python. When I program it do you follow BEDMAS order of figuring out or is there a logical order. The syntax is correct but I keep being told it is not right
See the equation below to be programmed into python. What are the rules for telling Python to calculate something correctly where 5 is the exponent
Use Python to calculate (((1+2)∗3)/4)5
Exponentiation in Python is done with the ** operator.
For instance:
2**8
is 256.
In Python to calculate exponent you use ** operator.
Similar to multiplication but double asterisk.
(((1+2)∗3)/4)**5
This will give you 32.
That is because you are using values which are all integers, so 9 / 4 will be 2, not 2.25.
Python has operator precedence that follows algebraic rules.

Large integers addition error in python 2.7.10 [duplicate]

This question already has answers here:
What do numbers starting with 0 mean in python?
(9 answers)
Closed 7 years ago.
I am trying to solve a problem using python. In which I have to deal with large integers (upto 500 digits). According to my current stage of understanding, python can handle any numbers in same traditional way. But I have problem in simple addition like this:
>>> p= 1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010
>>> q= 0011111011111010111101111110101101111001111111100011111101101100100011010011111011111110110011111000
>>> p+q
1001101111105557844987142979708366943425581971579987152809865568761000527613931421735161949470823522L
Can anyone please explain why i got such an error.
Var q starts with a zero, making it an octal number, rather than decimal

How to undo a string and calculate [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
parsing math expression in python and solving to find an answer
How can I "undo" a string with plus and addition signs in order to calculate them?
I have a string for example:
'6*1+7*1+1*7'
I tried int() but I've got error. How can I undo this whole string to just get a pure integer calculation?
You have to actually implement the operations you want to support by parsing the string and calculating the result. A trivial parser would look like:
>>> import functools,operator
>>> sum(functools.reduce(operator.mul, map(int, summand.split('*')), 1)
... for summand in '6*1+7*1+1*7'.split('+'))
20
Note that the built-in eval may work in a one-off script or an interactive console, but it interprets the string as Python source and therefore allows anyone who controls the string (i.e. the user) to execute arbitrary Python commands.
use eval():
In [177]: eval('6*1+7*1+1*7')
Out[177]: 20
or exec:
In [188]: exec compile('6*1+7*1+1*7','None','single')
Out[188]: 20

Categories