Pages

Showing posts with label PFOTD. Show all posts
Showing posts with label PFOTD. Show all posts

Saturday, November 2, 2013

PFOTD: Python ord() function examples

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()

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()