I have a tuple of tuples from a MySQL query like this:
T1 = ((\'13\', \'17\', \'18\', \'21\', \'32\'),
(\'07\', \'11\', \'13\', \'14\', \'28\'),
Try this.
x = "1"
x is a string because it has quotes around it, but it has a number in it.
x = int(x)
Since x has the number 1 in it, I can turn it in to a integer.
To see if a string is a number, you can do this.
def is_number(var):
try:
if var == int(var):
return True
except Exception:
return False
x = "1"
y = "test"
x_test = is_number(x)
print(x_test)
It should print to IDLE True because x is a number.
y_test = is_number(y)
print(y_test)
It should print to IDLE False because y in not a number.
In Python 3.5.1 things like these work:
c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))
and
Enter number: 4.7
4
5
George.
See this function
def parse_int(s):
try:
res = int(eval(str(s)))
if type(res) == int:
return res
except:
return
Then
val = parse_int('10') # Return 10
val = parse_int('0') # Return 0
val = parse_int('10.5') # Return 10
val = parse_int('0.0') # Return 0
val = parse_int('Ten') # Return None
You can also check
if val == None: # True if input value can not be converted
pass # Note: Don't use 'if not val:'
Instead of putting int( )
, put float( )
which will let you use decimals along with integers.
Using list comprehensions:
t2 = [map(int, list(l)) for l in t1]
I would rather prefer using only comprehension lists:
[[int(y) for y in x] for x in T1]