Syber
Syber

Reputation: 451

converting chr() / ord() with multi characters

beginner programming in python (3.4)
is it possible to pass multiple values inside chr() and ord()? what i tried is the following:

userInput = input('Please write your input: ')
> Hello
result = ord(userInput) #here is the error because i put multiple values instead of just one
print(result)

this is the output i am looking for: 72 101 108 108 111 (hello) but instead i get an error telling me i can only pass 1 character/value inside chr() / ord() is this possible? if not can you provide me in the right direction? thank you

Upvotes: 1

Views: 2481

Answers (3)

Kasravnd
Kasravnd

Reputation: 107347

You can use map function, in order to apply the ord on all characters separately:

In [18]: list(map(ord, 'example'))
Out[18]: [101, 120, 97, 109, 112, 108, 101]

Or use bytearray directly on string:

In [23]: list(bytearray('example', 'utf8'))
Out[23]: [101, 120, 97, 109, 112, 108, 101]

But note that when you are dealing with unicodes bytearray doesn't return a number like ord but an array of bytes values based on the passed encoding (a number between 0 and 256):

In [27]: list(bytearray('€', 'utf8'))
Out[27]: [226, 130, 172]

In [25]: ord('€')
Out[25]: 8364

Upvotes: 1

Mureinik
Mureinik

Reputation: 311998

You could use a list comprehension to apply ord to every character of the string, and then join them to get the result you're looking for:

result = " ".join([str(ord(x)) for x in userInput])

Upvotes: 0

hpaulj
hpaulj

Reputation: 231605

Use a list comprehension - apply ord to each character in the string.

In [777]: [ord(i) for i in 'hello']
Out[777]: [104, 101, 108, 108, 111]

Upvotes: 1

Related Questions