user3801907
user3801907

Reputation: 25

How do you change every character in a file into its ASCII number? Python

with open('s.txt', 'r') as f: s = f.read() 

for word in s:

    val = ord(word)

I'm trying to convert every character in the text file into its ASCII number, however it is only displaying one number when printed. Thank you.

Upvotes: 1

Views: 646

Answers (3)

idjaw
idjaw

Reputation: 26580

You are constantly overwriting your val, so you will actually only end up with the last ascii value. Also, for the sake of naming things properly, your iterator should be something like char or c. Using word is misleading.

You can do this:

new_data = " ".join(str(ord(c)) for c in f.read())

f.read() giving a string, we iterate over the string, grabbing each character, and then calling ord on each. Then cast it to a str (since ord returns an int) and finally join to change it back to the string of ascii values.

Upvotes: 1

Serdmanczyk
Serdmanczyk

Reputation: 1224

You're reassigning val every iteration, you should be appending it to an array or concatentating a string. e.g.:

with open('s.txt', 'r') as f:
    file_contents = f.read() 

ascii_vals = [ord(char) for char in file_contents]
print(ascii_vals)

Which is equivalent to the following if you're not yet familiar with list comprehensions (which execute a bit more efficiently).

with open('s.txt', 'r') as f:
    file_contents = f.read() 

ascii_vals = []
for char in file_contents]
    ascii_vals.append(ord(char))
print(ascii_vals)

Since ord gives an int value you'll have to do string formatting to convert back from int to string. How you do that depends how you want to present the data.

Don't forget if you're reading a file in utf-8 format you may get characters that go beyond what ASCII defines.

Upvotes: 0

Keatinge
Keatinge

Reputation: 4341

text = "hello 123 &^@!)(" #this is the example string

for character in list(text): #loops through every character
    print(ord(character)) #print the ascii value of the character

Upvotes: 0

Related Questions