Dumb noob q: ASCII value of a character

S

Steve Horsley

How can I get the ASCII value of a character, e.g. I have:

str = "A B"
for index in range(0, len(str)):
value = WHAT_GOES_HERE?(str[index])
print value


and I hope to get:
65
32
66


I know the characters will be printable ASCII.
But how do I get those ASCII character values from the characters???
I can't seem to find it in the library reference

Thanks,
Steve
 
P

Peter Hansen

Steve said:
How can I get the ASCII value of a character, e.g. I have:

str = "A B"
for index in range(0, len(str)):
value = WHAT_GOES_HERE?(str[index])
print value

and I hope to get:
65
32
66

I know the characters will be printable ASCII.
But how do I get those ASCII character values from the characters???
I can't seem to find it in the library reference

It's a good idea to read through all the builtin functions, as
documented in http://www.python.org/doc/current/lib/built-in-funcs.html#built-in-funcs
and keep them in mind.

In this case, ord() (and it's inverse chr()) are what you want.

-Peter
 
V

vincent wehren

Steve Horsley said:
How can I get the ASCII value of a character, e.g. I have:

str = "A B"
for index in range(0, len(str)):
value = WHAT_GOES_HERE?(str[index])
print value


and I hope to get:
65
32
66

Hi Steve,

a word of advice: do not use the name of an existing function as identifier
for
a variable ( I am referring to your usage of str as the name of the
variable - you are reassigning it!!!). But back to your question:
What you're looking for is:

s = "A B"
for c in s:
print ord(c)

HTH,

Vincent Wehren






know the characters will be printable ASCII.
 
J

John Hazen

* Steve Horsley said:
How can I get the ASCII value of a character, e.g. I have:

str = "A B"
for index in range(0, len(str)):
value = WHAT_GOES_HERE?(str[index])
print value


and I hope to get:
65
32
66

ord.

(And yes, it's a little hard to find. The first time I had to
solve this problem, I used:
65

)

Also of note: Strings can be used as iterators, so there's no need to
use that indexing trick:
.... print ord(char)
....
65
32
66

-John
< my_first_name AT my_last_name DOT net >
 
S

Steve Horsley

vincent said:
What you're looking for is:

s = "A B"
for c in s:
print ord(c)
Thank you everyone who answered.

Also, "for c in s:" - hmmm , still learning fast!
Also, overriding str funcion with a local variable - and STILL learning fast!

Regards,
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top