Home > Software engineering >  How to convert value of a String into it's specific datatype? '5' -> 5 OR 'a&
How to convert value of a String into it's specific datatype? '5' -> 5 OR 'a&

Time:06-24

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

CodePudding user response:

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]

CodePudding user response:

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.

CodePudding user response:

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]

CodePudding user response:

try this:

a = "123"
b = int(a)

CodePudding user response:

    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]
  1. If provided value is int it enters into if value.isdigit() and converts value into int.
  2. if value is float then value.isdigit() is false and enters into if value.replace('.', '', 1).isdigit() where . will be replaced and verifies whether digit or not. If it is digits then converts into float.
  • Related