Consider I take a input as a python list and it contains values like ['1', '5', 't', 'John', '3.18']
How to convert every value into its specific data type?
Something like this
String '1' -> Integer 1
String 't' -> Char 't'
String '3.18' -> Float 3.18
Ask for forgiveness, not permission!
def to_type(x):
try:
return int(x)
except ValueError:
pass
try:
return float(x)
except ValueError:
pass
return x
converted = [to_type(x) for x in your_list]
values = ['1', '5', 't', 'John', '3.18']
x=[int(value) if value.isdigit() else float(value) if value.replace('.', '', 1).isdigit() else value for value in values]
print(x)
Output:
[1, 5, 't', 'John', 3.18]
The type of data in the values list is not clear, so there is a possibility of an unexpected error.
values = ['1', '5', 't', 'John', '3.18']
def change_type(value):
if str(value).isdigit():
return int(value)
try:
return float(value)
except ValueError:
return value
[change_type(value) for value in values]
[1, 5, 't', 'John', 3.18]
You can use try except
structure to check whether an object can be converted to a specific data type:
l1 = ['1', '5', 't', 'John', '3.18']
#First object can be converted to int
try:
l1[0] = int(l1[0])
except ValueError as e:
print(e)
#Second one not
try:
l1[2] = int(l1[2])
except ValueError as e:
print(e)
print(l1)
In this case, the output would be:
invalid literal for int() with base 10: 't'
[1, '5', 't', 'John', '3.18']
You can use several checking using functions like int()
, float()
, bool()
.... You may need to check the Python official documentation to see all possibilities.
try this:
a = "123"
b = int(a)
You could use the ast.literal_eval()
function to parse the elements of the list the way the Python interpreter does. The code below would also work for tuples of strings.
from ast import literal_eval
def convert_seq(seq):
"""Return sequence of strings into one with each parsed as a literal value."""
def convert_elem(elem):
try:
return literal_eval(elem)
except ValueError:
return elem
return type(seq)(map(convert_elem, seq))
r = convert_seq(['1', '5', 't', 'John', '3.18', '"100"'])
print(r) # -> [1, 5, 't', 'John', 3.18, '100']
try this:
def check_(x):
if "." in x:
new_x = x.replace(".","",1)
if new_x.isdigit():
xx= float(x)
return "float",xx
if x.isdigit():
xx=int(x)
return "int",xx
else:
if len(x)>1:
xx=x
return "String",xx
else:
xx= x
return "char",xx
var_ = "55.3"
print(check_(var_)[0])
print(check_(var_)[1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.