Today our inbuilt function is ord() which is useful for converting a single character to its corresponding ASCII value.
Need of ord() function in Python:
Some times it is require to convert a string to unicode ASCII value and this inbuilt function will give python this capability.
ord() function syntax:
ord('char')
Examples: Let us start with ord() function with some examples and see how we can use them in Python coding.
Example1: Convert a char to its corresponding ascii value.
>>> ord('a')
Output:
97
>>>
Example2: Convert a string to ascii values.
>>> string='Hello World'
>>> for i in string:
... print ord(i)
...
Output:
72
101
108
108
111
32
87
111
114
108
100
Example3: Not satesfied with the output and want to convert a string to list of its corsponding ascii vlaues? use following code
>>> string='Hello World'
>>> list_ascii=[ord(i) for i in string]
>>> print list_ascii
Output:
[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
Related functions: chr(), int()
0 comments:
Post a Comment