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.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018