Today our in-built function is chr() which is useful for converting an ASCII value to it’s corresponding character.
Need of chr() function in Python:
Some times it requires to convert an ASCII value to it’s corsponding character and this in-built function will give python this capability.
Python chr function Syntax:
chr(number)
Examples: Let us start with chr() function with some examples and see how we can use them in Python coding.
Example1: Convert an ASCII value to it’s corresponding character.
>>> chr(97)
Output:
'a' >>>
Example2: Convert a string to an ASCII values.
>>>list_ascii=[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] >>> for i in list_ascii: ... print chr(i) ...
Output:
H
e
l
l
o
W
o
r
l
d
>>>
Example3: Not satisfied with the output and want to convert an ASCII to list of it’s corresponding characters? Use following code
>>>list_ascii=[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] >>> list_char=[chr(i) for i in list_ascii] >>> print list_char['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] >>> str1=''.join(list_char) >>> print str1 Hello World
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