Python Convert str to int/float, dict/list to str, and vice versa

eye-catch Python
Sponsored links

String to float

Just cast the string with float.

print(float("15"))  # 15.0
print(float("15.99"))  # 15.99
Sponsored links

Check if the string can be converted before cast

The string might need to be checked first whether it’s a numeric value or not. The following way can be used if it’s an integer value.

print("--- isnumeric ---")
print('13'.isnumeric()) # True
print("13".isnumeric()) # True
print("1/2".isnumeric()) # False
print("13.123".isnumeric()) # False
print("0x12".isnumeric())   # False

print("--- isdigit ---")
print('13'.isdigit()) # True
print("13".isdigit()) # True
print("1/2".isdigit()) # False
print("13.123".isdigit()) # False
print("0x12".isdigit())   # False

print("--- isdecimal ---")
print('13'.isdecimal()) # True
print("13".isdecimal()) # True
print("1/2".isdecimal()) # False
print("13.123".isdecimal()) # False
print("0x12".isdecimal())   # False

But all of them don’t work for float value. We need to define a function if it’s necessary to check whether it’s float or not.

def is_float(txt):
    try:
        float(txt)
        return True
    except ValueError:
        return False

print("--- is_float ---")
print(is_float('13')) # True
print(is_float("13")) # True
print(is_float("1/2")) # False
print(is_float("13.123")) # True
print(is_float("0x12") )  # False

Hmm… It looks not nice. It’s better directly to try to cast the string to float in the actual code.

String to int

If the string is an integer value, it can be directly converted to int. However, it must be converted to float first if it’s a float value.

print(int("15"))  # 15.0
try:
    print(int("15.99"))
except ValueError as err:
    # invalid literal for int() with base 10: '15.99'
    print(err)

print(int(float("15.99"))) # 15.99

int accepts the second parameter to indicate the base. If the string is bit string like 01010011, set 2 to the second parameter. If it’s HEX value, set 16.

print(int("11", 2))  # 3
print(int("11", 10))  # 11
print(int("11", 16))  # 17
print(int("FF", 16))  # 255

List to String

How can we convert a list to a string? str can be called for List directly but it contains brackets in this case.

list1 = [1, 2, 3, 4, 5]
print(str(list1))  # [1, 2, 3, 4, 5]

If only values need to be shown, the values need to be concatenated as a string. str.join() method can be used for this purpose but it requires iterable. Since list is not iterable, we need to use map.

listMap = map(str, list1)
print(",".join(listMap))  # 1,2,3,4,5

Only the values are shown as expected.

Dict to string

The same technique can be applied to Dict. The default string conversion contains the curly braces.

dict1 = {"key1": 11, "key2": 22, "key3": 33}
print(str(dict1))  # {'key1': 11, 'key2': 22, 'key3': 33}

Dict keys to string

The string dict_keys is not necessary.

print(str(dict1.keys()))  # dict_keys(['key1', 'key2', 'key3'])

So, it needs to be converted by map.

keyMap = map(str, dict1.keys())
print(list(keyMap))  # ['key1', 'key2', 'key3']

keyMap = map(str, dict1.keys())
print(",".join(keyMap))  # key1,key2,key3

As mentioned above, it needs to be joined by str.join() method.

Dict values to string

Likewise, we can get values.

print(str(dict1.values()))  # dict_values([11, 22, 33])

valueMap = map(str, dict1.values())
print(list(valueMap))  # ['11', '22', '33']

valueMap = map(str, dict1.values())
print(",".join(list(valueMap)))  # 11,22,33

Class to string

How can we implement it if a class need to be converted to string?

class MyClassA:
    def __init__(self, *, name, speed, private_prop, protedted_prop):
        self.name = name
        self.speed = speed
        self._protedted_value = protedted_prop
        self.__private_value = private_prop

myClassA = MyClassA(
    name="name A",
    speed=50,
    protedted_prop="protected value",
    private_prop="private value",
)

print(str(myClassA))  # <__main__.MyClassA object at 0x7fb1b59c7ee0>

If a class is converted to a string, the string text is meaningless. If the class is our own class, we need to define __str__ function. __str__ is called when str() is called.

class MyClassA:
    def __init__(self, *, name, speed, private_prop, protedted_prop):
        self.name = name
        self.speed = speed
        self._protedted_value = protedted_prop
        self.__private_value = private_prop

    def __str__(self):
        return f"name: {self.name}, speed: {self.speed}, protected: {self._protedted_value}, private: {self.__private_value}"


myClassA = MyClassA(
    name="name A",
    speed=50,
    protedted_prop="protected value",
    private_prop="private value",
)

print(str(myClassA))
# name: name A, speed: 50, protected: protected value, private: private value

Comments

Copied title and URL