Pages

Saturday, November 2, 2013

PFOTD: Python chr() function example

Today our in-built function is chr() which is useful for converting an ASCII value to its corresponding character.

Need of chr() function in Python:


Some times it requires to convert an unicode ASCII value to its 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 its 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 its 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()

 

0 comments:

Post a Comment