How do I prevent spaces when using Python? - python

How would I remove the spaces after the R in the following line?
>>>print "4/3 =", 4 / 3, "R", 4 % 3
I want the result to look exactly like this:
4/3 = 1 R1
I appreciate any time anyone takes to answer this question.

Use str.format:
>>> a=4
>>> b=3
>>> print "{}/{} = {} R{}".format(a, b, a//b, a%b)
4/3 = 1 R1
If you are using an older version of Python which doesn't support str.format then you can use the % operator:
>>> print "%d/%d = %d R%d"%(a, b, a//b, a%b)
4/3 = 1 R1
Note also that since Python 2.2 you should use // for integer division, and from Python 3 onwards, you must use //.

You should use formatting.
print "4/3 = %d R%d" % (4 / 3, 4 % 3)
or even better, with string.format:
print "4/3 = {} R{}".format(4 / 3, 4 % 3)

You should use string format
print "4/3 =%d R%d" % (4 / 3, 4 % 3)

Related

Optimized summing beween ints and strs [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 2 years ago.
print("ax^2 + bx + c = d what is your values for them? ")
a = int(input(">a = "))
b = int(input(">b = "))
c = int(input(">c = "))
d = int(input(">d = "))
given_parabola = str(a) + "x^2 + " + str(b) + "x + " + (str(c)) + " = " + str(d)
Is there any other way that I can merge integer variables with strings?
The "best" approach really depends on what you're trying to do.
1. Concatenating lists with variable number of items (numbers and strings)
If you simply want to form a string from numbers and strings, I would first create a generator with generator expression and then join the strings with the join() method.
In [1]: a = [2, 'a', 3, 'x', 'foo', 8, 55]
In [2]: g = (str(x) for x in a)
In [3]: ' '.join(g)
Out[3]: '2 a 3 x foo 8 55'
Pluses
Can be used to concatenate any amount of strings and numbers, which can be in any order
Minuses
Probably not the most speed optimized, if you know more about the variables you are going to concatenate
2. Literal String interpolation
If you know what amount of numeric variables you want to concatenate with what strings, the problem is called string interpolation.
In Python 3.6+ you can use so-called f-strings to form string using a string template and a fixed number of variables. For example:
In [1]: a, b, c, d = 3, 2, 1, 5
In [2]: f"{a}x^2 + {b}x + {c} = {d}"
Out[2]: '3x^2 + 2x + 1 = 5'
Pluses
Probably the most speed optimized way to create a string from a template.
Minuses
This is not a general approach to "sum"/concatenate any amount of strings and numbers.
3. Using sympy for expression generation
Since your problem looks like being very specific: You want to create string from mathematical formula, you might want to look at sympy.
Installation
pip install sympy
Simple example
In [1]: from sympy import symbols, Eq, mathematica_code
In [2]: x, a, b, c, d = symbols('x a b c d')
In [3]: expr = Eq(a*(x**2) + b*x + c, d)
In [4]: var_dict = dict(a=3, b=2, c=1, d=5)
In [5]: expr_with_numbers = expr.subs(var_dict)
In [6]: mathematica_code(expr_with_numbers).replace('==', '=')
Out[6]: '3*x^2 + 2*x + 1 = 5'
you can also solve for the expression easily:
In [7]: solve(expr_with_numbers, x)
Out[7]: [-1/3 + sqrt(13)/3, -sqrt(13)/3 - 1/3]
and you can print any kind of equation. For example
In [1]: from sympy import symbols, Eq, mathematica_code, sqrt, pretty, solve
In [2]: expr = Eq(a*(x**2)/(sqrt(x-c)), d)
In [3]: var_dict = dict(a=3, b=2, c=1, d=5)
In [4]: expr_with_numbers = expr.subs(var_dict)
In [5]: print(pretty(expr_with_numbers, use_unicode=False))
2
3*x
--------- = 5
_______
\/ x - 1
Pros
Useful, if you want to create complex mathematical expressions
Can also output pretty multiline output or even LaTeX output.
Can be useful if you want to actually solve the equation, too
Cons
Not speed-optimized for simple string formation.
You can avoid concatenating multiple strings using the format string python proposed.
Using Format strings vs concatenation to do a list of more performant to less performant
f-string as f"{a}x^2 + {b}x + {c} = {d}"
"%sx^2 + %sx + %s = %s" % (a,b,c,d)
"{}x^2 + {}x + {} = {}".format(a,b,c,d)
Might I suggest string interpolation?
given_parabola = "%sx^2 + %sx + %s = %s" % (a, b, c, d)
Or
given_parabola = f"{a}x^2 + {b}x + {c} = {d}"
Yes, hopefully, this is what you mean:
# This way the integer 10 will convert to a string automatically. Works in Print as well!
x = 10
y = "lemons"
z = "In the basket are %s %s" % (x, y)
print(z)
Output:
In the basket are 10 lemons

How to convert a float into format of 0.####e# in python [duplicate]

How can I display Decimal('40800000000.00000000000000') as '4.08E+10'?
I've tried this:
>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'
But it has those extra 0's.
from decimal import Decimal
'%.2E' % Decimal('40800000000.00000000000000')
# returns '4.08E+10'
In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.
If you want to remove all trailing zeros automatically, you can try:
def format_e(n):
a = '%E' % n
return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]
format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'
format_e(Decimal('40000000000.00000000000000'))
# '4E+10'
format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'
Here's an example using the format() function:
>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'
Instead of format, you can also use f-strings:
>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'
official documentation
original format() proposal
Given your number
x = Decimal('40800000000.00000000000000')
Starting from Python 3,
'{:.2e}'.format(x)
is the recommended way to do it.
e means you want scientific notation, and .2 means you want 2 digits after the dot. So you will get x.xxE±n
No one mentioned the short form of the .format method:
Needs at least Python 3.6
f"{Decimal('40800000000.00000000000000'):.2E}"
(I believe it's the same as Cees Timmerman, just a bit shorter)
This is a consolidated list of the "Simple" Answers & Comments.
PYTHON 3
from decimal import Decimal
x = '40800000000.00000000000000'
# Converted to Float
x = Decimal(x)
# ===================================== # `Dot Format`
print("{0:.2E}".format(x))
# ===================================== # `%` Format
print("%.2E" % x)
# ===================================== # `f` Format
print(f"{x:.2E}")
# =====================================
# ALL Return: 4.08E+10
print((f"{x:.2E}") == ("%.2E" % x) == ("{0:.2E}".format(x)))
# True
print(type(f"{x:.2E}") == type("%.2E" % x) == type("{0:.2E}".format(x)))
# True
# =====================================
OR Without IMPORT's
# NO IMPORT NEEDED FOR BASIC FLOATS
y = '40800000000.00000000000000'
y = float(y)
# ===================================== # `Dot Format`
print("{0:.2E}".format(y))
# ===================================== # `%` Format
print("%.2E" % y)
# ===================================== # `f` Format
print(f"{y:.2E}")
# =====================================
# ALL Return: 4.08E+10
print((f"{y:.2E}") == ("%.2E" % y) == ("{0:.2E}".format(y)))
# True
print(type(f"{y:.2E}") == type("%.2E" % y) == type("{0:.2E}".format(y)))
# True
# =====================================
Comparing
# =====================================
x
# Decimal('40800000000.00000000000000')
y
# 40800000000.0
type(x)
# <class 'decimal.Decimal'>
type(y)
# <class 'float'>
x == y
# True
type(x) == type(y)
# False
x
# Decimal('40800000000.00000000000000')
y
# 40800000000.0
So for Python 3, you can switch between any of the three for now.
My Fav:
print("{0:.2E}".format(y))
See tables from Python string formatting to select the proper format layout. In your case it's %.2E.
This worked best for me:
import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10
My decimals are too big for %E so I had to improvize:
def format_decimal(x, prec=2):
tup = x.as_tuple()
digits = list(tup.digits[:prec + 1])
sign = '-' if tup.sign else ''
dec = ''.join(str(i) for i in digits[1:])
exp = x.adjusted()
return '{sign}{int}.{dec}e{exp}'.format(sign=sign, int=digits[0], dec=dec, exp=exp)
Here's an example usage:
>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
3.39e7800
>>> print '%e' % n
inf
To convert a Decimal to scientific notation without needing to specify the precision in the format string, and without including trailing zeros, I'm currently using
def sci_str(dec):
return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)
print( sci_str( Decimal('123.456000') ) ) # 1.23456E+2
To keep any trailing zeros, just remove the normalize().
I prefer Python 3.x way.
cal = 123.4567
print(f"result {cal:.4E}")
4 indicates how many digits are shown shown in the floating part.
cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
Adding an updated answer to show how to apply e notation to small numbers only
value = 0.1
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 0.1
value = 0.00002488
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 2.488e-05
Here is the simplest one I could find.
format(40800000000.00000000000000, '.2E')
#'4.08E+10'
('E' is not case sensitive. You can also use '.2e')
def formatE_decimal(x, prec=2):
""" Examples:
>>> formatE_decimal('0.1613965',10)
'1.6139650000E-01'
>>> formatE_decimal('0.1613965',5)
'1.61397E-01'
>>> formatE_decimal('0.9995',2)
'1.00E+00'
"""
xx=decimal.Decimal(x) if type(x)==type("") else x
tup = xx.as_tuple()
xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
tup = xx.as_tuple()
exp = xx.adjusted()
sign = '-' if tup.sign else ''
dec = ''.join(str(i) for i in tup[1][1:prec+1])
if prec>0:
return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
elif prec==0:
return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
else:
return None

Display floating point number in decimal form in Python?

Let's say I have the following float point number in Python
>>>a = 10 ** -10
>>>print a
1e-10
How can I display .0000000001 instead of 1e-10?
>>> a = "%0.10f" % (10 ** -10)
>>> a
'0.0000000001'
Maybe a bit more readable:
a = float("1e-10")
format(a, ".10f")
Output
'0.0000000001'
Or using format
>>> a = 10 ** -10
>>> '{a:0.10f}'.format(a=a)

Can't convert Celsius to Fahrenheit

Here's my code:
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
fah = float((temp*9/5)+32)
fah_two = (%.2f) % fah
fah_string = str(fah_two)
return fah_string
Here's what I should get:
>>> Cel2Fah(28.0)
'82.40'
>>> Cel2Fah(0.00)
'32.00'
But I get an error:
Traceback (most recent call last):
File "Code", line 4
fah_two = (%.2f) % fah
^
SyntaxError: invalid syntax
I'm not sure what is going on...
This doesn't seem to work either for some reason:
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
fah = temp*9/5+32
fah_cut = str(fah).split()
while len(fah_cut) > 4:
fah_cut.pop()
fah_shorter = fah_cut
return fah_shorter
It looks like you want:
fah_two = "%.2f" % fah
The result of the % formatting operator is a string, so you don't need fah_string because fah_two is already a string.
sucmac:~ ajung$ cat x.py
def toF(cel):
return '%.2f' % (cel * 1.8 +32)
print toF(0)
print toF(50)
print toF(100)
sucmac:~ ajung$ python x.py
32.00
122.00
212.00
Further, I think temp * 9 / 5 should be temp * 9 / 5.0.

drop trailing zeros from decimal

I have a long list of Decimals and that I have to adjust by factors of 10, 100, 1000,..... 1000000 depending on certain conditions. When I multiply them there is sometimes a useless trailing zero (though not always) that I want to get rid of. For example...
from decimal import Decimal
# outputs 25.0, PROBLEM! I would like it to output 25
print Decimal('2.5') * 10
# outputs 2567.8000, PROBLEM! I would like it to output 2567.8
print Decimal('2.5678') * 1000
Is there a function that tells the decimal object to drop these insignificant zeros? The only way I can think of doing this is to convert to a string and replace them using regular expressions.
Should probably mention that I am using python 2.6.5
EDIT
senderle's fine answer made me realize that I occasionally get a number like 250.0 which when normalized produces 2.5E+2. I guess in these cases I could try to sort them out and convert to a int
You can use the normalize method to remove extra precision.
>>> print decimal.Decimal('5.500')
5.500
>>> print decimal.Decimal('5.500').normalize()
5.5
To avoid stripping zeros to the left of the decimal point, you could do this:
def normalize_fraction(d):
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
return decimal.Decimal((sign, digits + (0,) * exponent, 0))
else:
return normalized
Or more compactly, using quantize as suggested by user7116:
def normalize_fraction(d):
normalized = d.normalize()
sign, digit, exponent = normalized.as_tuple()
return normalized if exponent <= 0 else normalized.quantize(1)
You could also use to_integral() as shown here but I think using as_tuple this way is more self-documenting.
I tested these both against a few cases; please leave a comment if you find something that doesn't work.
>>> normalize_fraction(decimal.Decimal('55.5'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55.500'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55500'))
Decimal('55500')
>>> normalize_fraction(decimal.Decimal('555E2'))
Decimal('55500')
There's probably a better way of doing this, but you could use .rstrip('0').rstrip('.') to achieve the result that you want.
Using your numbers as an example:
>>> s = str(Decimal('2.5') * 10)
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
25
>>> s = str(Decimal('2.5678') * 1000)
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
2567.8
And here's the fix for the problem that #gerrit pointed out in the comments:
>>> s = str(Decimal('1500'))
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
1500
Answer from the Decimal FAQ in the documentation:
>>> def remove_exponent(d):
... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5.00'))
Decimal('5')
>>> remove_exponent(Decimal('5.500'))
Decimal('5.5')
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
Answer is mentioned in FAQ (https://docs.python.org/2/library/decimal.html#decimal-faq) but does not explain things.
To drop trailing zeros for fraction part you should use normalize:
>>> Decimal('100.2000').normalize()
Decimal('100.2')
>> Decimal('0.2000').normalize()
Decimal('0.2')
But this works different for numbers with leading zeros in sharp part:
>>> Decimal('100.0000').normalize()
Decimal('1E+2')
In this case we should use `to_integral':
>>> Decimal('100.000').to_integral()
Decimal('100')
So we could check if there's a fraction part:
>>> Decimal('100.2000') == Decimal('100.2000').to_integral()
False
>>> Decimal('100.0000') == Decimal('100.0000').to_integral()
True
And use appropriate method then:
def remove_exponent(num):
return num.to_integral() if num == num.to_integral() else num.normalize()
Try it:
>>> remove_exponent(Decimal('100.2000'))
Decimal('100.2')
>>> remove_exponent(Decimal('100.0000'))
Decimal('100')
>>> remove_exponent(Decimal('0.2000'))
Decimal('0.2')
Now we're done.
Use the format specifier %g. It seems remove to trailing zeros.
>>> "%g" % (Decimal('2.5') * 10)
'25'
>>> "%g" % (Decimal('2.5678') * 1000)
'2567.8'
It also works without the Decimal function
>>> "%g" % (2.5 * 10)
'25'
>>> "%g" % (2.5678 * 1000)
'2567.8'
I ended up doing this:
import decimal
def dropzeros(number):
mynum = decimal.Decimal(number).normalize()
# e.g 22000 --> Decimal('2.2E+4')
return mynum.__trunc__() if not mynum % 1 else float(mynum)
print dropzeros(22000.000)
22000
print dropzeros(2567.8000)
2567.8
note: casting the return value as a string will limit you to 12 significant digits
Slightly modified version of A-IV's answer
NOTE that Decimal('0.99999999999999999999999999995').normalize() will round to Decimal('1')
def trailing(s: str, char="0"):
return len(s) - len(s.rstrip(char))
def decimal_to_str(value: decimal.Decimal):
"""Convert decimal to str
* Uses exponential notation when there are more than 4 trailing zeros
* Handles decimal.InvalidOperation
"""
# to_integral_value() removes decimals
if value == value.to_integral_value():
try:
value = value.quantize(decimal.Decimal(1))
except decimal.InvalidOperation:
pass
uncast = str(value)
# use exponential notation if there are more that 4 zeros
return str(value.normalize()) if trailing(uncast) > 4 else uncast
else:
# normalize values with decimal places
return str(value.normalize())
# or str(value).rstrip('0') if rounding edgecases are a concern
You could use :g to achieve this:
'{:g}'.format(3.140)
gives
'3.14'
This should work:
'{:f}'.format(decimal.Decimal('2.5') * 10).rstrip('0').rstrip('.')
Just to show a different possibility, I used to_tuple() to achieve the same result.
def my_normalize(dec):
"""
>>> my_normalize(Decimal("12.500"))
Decimal('12.5')
>>> my_normalize(Decimal("-0.12500"))
Decimal('-0.125')
>>> my_normalize(Decimal("0.125"))
Decimal('0.125')
>>> my_normalize(Decimal("0.00125"))
Decimal('0.00125')
>>> my_normalize(Decimal("125.00"))
Decimal('125')
>>> my_normalize(Decimal("12500"))
Decimal('12500')
>>> my_normalize(Decimal("0.000"))
Decimal('0')
"""
if dec is None:
return None
sign, digs, exp = dec.as_tuple()
for i in list(reversed(digs)):
if exp >= 0 or i != 0:
break
exp += 1
digs = digs[:-1]
if not digs and exp < 0:
exp = 0
return Decimal((sign, digs, exp))
Why not use modules 10 from a multiple of 10 to check if there is remainder? No remainder means you can force int()
if (x * 10) % 10 == 0:
x = int(x)
x = 2/1
Output: 2
x = 3/2
Output: 1.5

Categories