1

Here is the background information: I have a .txt file with some numbers on it that are all separated by commas. Then, using Python code, I opened it and read it. After that, I made a list out of all of the numbers that were on the file. When I made a list, the numbers were all strings (example: '9', '8', etc.), so I used some Python code to convert the values of the list into integers. Now, I am trying to create some code so that I can convert all of the integers in the list to hexadecimal. The reason I want to create a piece of code instead of doing it manually is that there are around 20 numbers (in decimal format) and I want to convert them all into hexadecimal using some piece of Python code. Here is my code so far (until the point of converting the list to integers). Please help! I have tried to search so much on Google but could not find anything specific to this.

Code:

my_file = open(r'C:\Users\USER\Downloads\List of Numbers File.txt', encoding='utf-8-sig')

content = my_file.read()

print(content)

content_list = content.split(",")

my_file.close()

print(content_list)

for i in range(0, len(content_list)):
    content_list[i] = int(content_list[i])

print(str(content_list))
2
  • content_list[i] = hex(int(content_list[i])) ? Aug 23, 2020 at 7:49
  • Thank you to all those who answered! I really appreciate it.
    – Kapur
    Aug 23, 2020 at 20:35

4 Answers 4

1

Can be done in one line by

hex_list = [hex(int(x)) for x in content_list]
0
0

You can just wrap your int(content_list[i]) into the hex() function:

for i in range(0, len(content_list)):
    content_list[i] = hex(int(content_list[i]))
1
  • Thank you so much! This works as well, but I wanted something short and simple.
    – Kapur
    Aug 23, 2020 at 20:37
0

Use the built in hex() function:

hex(a) Where a is the integer to be converted.

1
  • This doesn't help because I don't want only one integer at a time. I want them all to be converted.
    – Kapur
    Aug 23, 2020 at 20:14
0

instead of multiple for loops you can use map function which applies given function to all elements in the list. You can use hex function to convert your numbers to hex code.

contents = map(int,content_list)
hex_contents = map(hex,contents)
2
  • For some reason, I cannot get all of the numbers in hexadecimal format when I try this.
    – Kapur
    Aug 23, 2020 at 20:36
  • If your strings cannot be converted to an integer then it may create wrong results but other than that if you can do with for loop it would be the same output. Aug 24, 2020 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.