Is there any other way to convert string to int? I need to do this without using this:
x = '345'
y = int(x)
Then it should work like this:
>>> function('456') + 5
461
You could use eval, but int works just fine for what you are trying.
>>> eval('123') + 5
128
def not_int(s):
if s.isdigit():
return eval(s)
raise ValueError("invalid literal: %r" % (s,))
Update: as posted in the comments, this only works for positive integers. It can be made to work with negative literals, but it gets more contrived for nothing, because int does exist! By the way, this does not even handle bases other than 10.
The following works better, and does not actually use int ;-)
def not_int(s):
return eval("int(%r)" % (s,))
Related
I wish to cast a string or a number to an integer only if the casting is "lossless" or, another way to put it, only if the string or number is indeed an integer.
For instance,
3.0 (a float that is indeed an integer) -> 3.
'3.000' (a string that is an integer) -> 3.
3.1 -> exception raised.
'4.2' -> exception raised.
Directly doing int(x) will convert 3.1 to 3.
This is the best I have:
def safe_cast_to_int(x):
int_x = int(x)
if np.issubdtype(type(x), np.floating):
assert int_x == x, \
f"Can't safely cast a non-integer value ({x}) to integer"
return int_x
but I wonder if there is a better or more Pythonic way?
If I understand you correctly, you only want to cast something if it's a whole number.
If that's the case, you could first cast it to a float and then check with float.is_integer() function if it's an integer.
Here are the examples with values of the question.
>>> float('3.0').is_integer()
True
>>> float('3.000').is_integer()
True
>>> float('3.1').is_integer()
False
>>> float('4.2').is_integer()
False
You could convert to float and modulus the data with 1 to check if you want to keep it a float
val = float(src)
val = int(val) if not val%1 else val
Edit: is_integer() is just doing the below for you, but with a bunch of conditions and flags attached before it gets to this line.
o = (floor(x) == x) ? Py_True : Py_False;
If you want things that look like integers, but aren't really integer values, as in (1.03-0.42)*100, then you need to test to see how "near" an integer a value is, and accept anything close. How close you accept as "integer" will depend on your exact use case:
import sys
tests = [
42,
'1.00',
3.2,
(1.03-0.42)*100,
]
for x in tests:
is_close_to_int = abs(int(float(x))-float(x))<0.00000000001
print(f"{x}: {float(x).is_integer()} {is_close_to_int}")
This outputs:
42: True True
1.00: True True
3.2: False False
61.00000000000001: False True
Showing that for many cases float's is_integer helper will do the right thing, but for some edge cases, a person might expect different results.
The aim is to return the middle letter of a string, or " " if the string's even. I'm failing to see why my code doesn't work. Any sort of clarification would be great, thanks!
def mid(ml):
x=len(ml)
y=x+1
z=y/2
if isinstance(z,int)==True:
return (ml[z-1])
else:
return (" ")
print (mid("abc"))
/ doesn't return an int; even if the number it returns can be represented as one:
>>> 4 / 2
2.0 # A float
It would be better to explicitly check if the number is even or not:
# Read as: "If z is odd", or, "If division of z by 2 has a remainder of 1"
if z % 2 == 1:
return ml[z-1]
else:
return " "
This behavior occurs, because the / operator returns a float. Although the smarter way to solve this would be the use of the modulo operator, if you want to stick to your code, could use the is_integer() method of float like this:
def mid(ml):
x=len(ml)
y=x+1
z=y/2
if z.is_integer():
return (ml[int(z)-1])
else:
return (" ")
print (mid("abc"))
Better way to do it:
def mid(ml):
return ml[len(ml)//2] if len(ml) % 2 else ""
Following the answer from #Carcigenicate above you can try following code:
def mid(ml):
x=len(ml)
y=x+1
z=y/2
return (ml[int(z-1)])
print (mid("abc"))
I wish to find a way to achieve the following: With the likes of 5.0, return 5. With the likes of 5.1, which cannot equal any integer, return Error.
Currently I use int() together with an "if integer != float". However this has problems, for instance I won't be able to tell whether the inequality was caused by the likes of 5.1 or the likes of 1111111111111111.0(and even larger numbers).
Also this is extremely troublesome compared with a potential, simple, one-line command. So is there a command in Python that does this?
Float objects in Python have an is_integer() predicate.
def strict_int(x):
if x.is_integer():
return int(x)
raise ValueError
Note that int objects do not have this method. You'll get an attribute error if you try to call this on an int.
If you wanted some error value instead of an exception, you can use a one-liner like this
int(x) if x.is_integer() else 'Error'
Simply use math as suggested in this answer by #Anthony V like this:
>>> frac, whole = math.modf(5.0)
>>> if frac ==0.0:
... print("this is a whole")
... else:
... print("this is not whole and should return the Error")
This should work easily.
I'm not sure whether there's a more idiomatic way to do this, but intuitively, you can just compare the value of the int and the float and return only when they are equal.
That is
def weird_cast(my_float):
if int(my_float) == my_float:
return int(my_float)
return None # or some error
def return_int(a):
if int(a)==a:
print(int(a)) #you can store the integer value in separate variable #also b = int(a)
#instead of using print you can use return b or int(a)
else:
print('Error') #or you can use return 'Error'
a = 5.0
return_int(a)
Maybe another easier way is to minus with the round down number with itself.
if the remainder is more than 0.0 and less than 1.0, then we can call it a float otherwise integer
def IntegerSanityCheck ( num ):
remainder = abs ( round ( num ) - num )
if ( remainder > 0.0 ) and ( remainder < 1.0 ):
print "Float"
else:
print "Integer"
or you can use math as suggested by user2906838
I have a list l = ['1','2','3','rt4','rt5']. I want to convert the numbers that are int type and keep the rest as is.
Desired output:
m = [1, 2, 3, 'rt4', 'rt5']
I tried it in following way
ord(m['rt4'])
it gave me the following error
"TypeError: ord() expected a character, but string of length 3 found"
it should works:
l = ['1','2','3','rt4','rt5']
def reformater(din):
try:
return int(din)
except Exception:
return din
s = [reformater(i) for i in l]
You can use the built-in int() function to convert a string to an integer. This function will throw an exception if the input string is not a valid integer, so you can just return the unmodified input in that case using the try..catch statement.
l = ['1','2','3','rt4','rt5']
def try_to_int(s):
try:
return int(s)
except:
return s
m = [try_to_int(it) for it in l]
print(m)
int() might however accept more formats as valid integers than you want, so you could also validate the integer explicitly.
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
l=['1','2','3','rt4','rt5']
l=[int(l[i]) if RepresentsInt(l[i]) else l[i] for i in range(0,len(l))]
making function which checks for int.
OR
l=['1','2','3','rt4','rt5']
l=[int(i) if i.isdigit() else i for i in l]
just using isdigit() built-in function.
When I am executing this code in http://www.pyschools.com/quiz/view_question/s2-q1. It gives error for both the answers... Please help
The questions is:
Write a function to convert temperature from Celsius to Fahrenheit scale.
oC to oF Conversion: Multipy by 9, then divide by 5, then add 32.
Examples
>>> Cel2Fah(28.0)
'82.40'
>>> Cel2Fah(0.00)
'32.00'
My Answer
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
x = 9.00
y = 5.00
z = 32.00
a = temp * x
a = a / y
a = a + z
return(a)
At the top it says:
# Note: Return a string of 2 decimal places.
You are not returning a string. You are returning a value of type float.
Since this looks like homework, I'll let you figure out how to fix this (hint: use the string formatting operator).
Return this instead.
return '%.2f' %a
change your return statement to read
return '%.2f' %a
There is nothing wrong syntactically with that code. It should work if you pass a number as parameter. It won't work if you pass anything but a number.
def Cel2Fah(temp):
cel=(round((((temp*9)/5) +32),2))
return '%.2f' %cel
print Cel2Fah(36.9)
print Cel2Fah(29.0)