![]() |
|
[Tut] Easiest Way to Convert List of Hex Strings to List of Integers - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Easiest Way to Convert List of Hex Strings to List of Integers (/thread-100287.html) |
[Tut] Easiest Way to Convert List of Hex Strings to List of Integers - xSicKxBot - 11-25-2022 Easiest Way to Convert List of Hex Strings to List of Integers 5/5 – (1 vote) Question: Given a Python list of hexadecimal strings such as Code: ['ff', 'ef', '0f', '0a', '93']Code: [255, 239, 15, 10, 147]Easiest Answer ![]() The easiest way to convert a list of hex strings to a list of integers in Python is the list comprehension statement Code: [int(x, 16) for x in my_list]Code: int()Code: 16Code: xHere’s a minimal example: Code: my_list = ['ff', 'ef', '0f', '0a', '93']
my_ints = [int(x, 16) for x in my_list] print(my_ints)
# [255, 239, 15, 10, 147]The list comprehension statement applies the expression Code: int(x, 16)Code: xCode: my_listThe Code: int(x, 16)Code: 16Code: int(x, base=16)In fact, there are many more ways to convert a hex string to an integer—each of them could be used in the expression part of the list comprehension statement. However, I’ll show you one completely different approach to solving this problem without listing each and every combination of possible solutions. ![]() For Loop with List Append You can create an empty list and add one hex integer at a time in the loop body after converting it from the hex string Code: xCode: eval('0x' + x)Code: '0x'Here’s an example: Code: my_list = ['ff', 'ef', '0f', '0a', '93'] my_ints = []
for x in my_list: my_ints.append(eval('0x' + x)) print(my_ints)
# [255, 239, 15, 10, 147]You use the fact that Python automatically converts a hex value of the form Code: 0xffCode: 255Code: >>> 0xff
255
>>> 0xfe
254
>>> 0x0f
15You may want to check out my in-depth guide on this important function for our solution: Recommended Tutorial: Python Code: eval() |