Today our inbuilt function is ord() short form of 'ordinal' which means a number defining the position of something in a series, such as ‘first’, ‘second’, or ‘third’. This function is useful for converting a single character to it’s corresponding ASCII value.

Need of ord() function in Python:

Some times it is require to convert a string to ASCII(American Standard Code for Information Interchange) value and this inbuilt function will give python this capability.

ord() function syntax:

	ord('single-char')

Examples: Let us start with ord() function with some examples and see how we can use them in Python.

Example1: Convert a char to it’s 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 satisfied with the output and want to convert a string to list of it’s coresponding ASCII values? 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()
Complete python built-in function list.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.