Ord() Function In Python - GeeksforGeeks

Skip to content geeksforgeeks
  • Courses
    • DSA Courses
    • Programming Languages
  • Tutorials
    • Python Tutorial
      • Python Loops and Control Flow
    • Java
      • Java Interview Questions
      • Java Quiz
      • Advance Java
    • Programming Languages
    • System Design
    • Interview Corner
    • Computer Science Subjects
    • DevOps
    • Linux
    • Software Testing
    • Databases
    • Android
    • Excel
    • Mathematics
  • DSA
    • Data Structures
    • Algorithms
      • Analysis of Algorithms
      • Searching Algorithms
      • Sorting Algorithms
    • Practice
      • Company Wise Coding Practice
      • Practice Problems Difficulty Wise
      • Language Wise Coding Practice
      • Curated DSA Lists
    • Company Wise SDE Sheets
    • DSA Cheat Sheets
    • Puzzles
  • Data Science
    • Data Science Packages
    • Data Visualization
    • Data Analysis
  • Web Tech
    • Web Development Using Python
      • Django
      • Flask
    • Cheat Sheets
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Lists
  • Strings
  • Dictionaries
Open In App ord() function in Python Last Updated : 30 Jun, 2023 Summarize Comments Improve Suggest changes Like Article Like Save Share Report Follow

Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a Unicode object, or the value of the byte when the argument is an 8-bit string.

Example

Here, ord(‘a’) returns the integer 97, ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive.

Python3

print(ord('a')) # Output: 97 print(ord('€')) # Output: 8364

Python ord() Syntax

Syntax: ord(ch)

Parameter : ch – A unicode character

How does ord work in Python?

In this example, We are showing the ord() value of an integer, character, and unique character with ord() function in Python.

Python3

print(ord('2')) print(ord('g')) print(ord('&'))

Output :

50 103 38

Note: If the string length is more than one, a TypeError will be raised. The syntax can be ord(“a”) or ord(‘a’), both will give the same results. The example is given below.

Demonstration of Python ord() function

This code shows that ord() value of “A”, ‘A’ gives the same result.

Python

# inbuilt function return an # integer representing the Unicode code value = ord("A") # writing in ' ' gives the same result value1 = ord('A') # prints the unicode value print (value, value1)

Output

65 65

Error Condition while Using Ord(0)

A TypeError is raised when the length of the string is not equal to 1 as shown below.

Python3

# inbuilt function return an # integer representing the Unicode code # demonstrating exception # Raises Exception value1 = ord('AB') # prints the unicode value print(value1)

Output

Traceback (most recent call last):

File “/home/f988dfe667cdc9a8e5658464c87ccd18.py”, line 6, in

value1 = ord(‘AB’)

TypeError: ord() expected a character, but string of length 2 found

Python ord() and chr() Functions

The chr() method returns a string representing a character whose Unicode code point is an integer.

Syntax: chr(num)

num : integer value

Where ord() methods work on the Unicodeopposite for chr() function.

Example of ord() and chr() functions

This code print() the Unicode of the character with the ord() and after getting the Unicode we are printing the character with the chr() function.

Python3

# inbuilt function return an # integer representing the Unicode code value = ord("A") # prints the unicode value print (value) # print the character print(chr(value))

Output

65 A

S

Striver Follow Improve Previous Article Python oct() Function Next Article Python pow() Function

Similar Reads

Wand function() function in Python function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp 1 min read Python - Call function from another function Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function 5 min read Returning a function from a function - Python Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi 4 min read Python math.sqrt() function | Find Square Root in Python sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root 3 min read wxPython - GetField() function function in wx.StatusBar In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in 1 min read How to write an empty function in Python - pass statement? In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa 1 min read Ways to sort list of dictionaries by values in Python - Using lambda function In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can 2 min read Python Numbers | choice() function choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P 1 min read Python | askopenfile() function in Tkinter While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to 2 min read Python | Binding function in Tkinter Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look 3 min read Python pow() Function Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modulus of mod on the result of x**y (i.e.: x**y % mod 2 min read Print powers using Anonymous Function in Python Prerequisite : Anonymous function In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, ano 2 min read Maximum length of consecutive 1's in a binary string in Python using Map function We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The a 1 min read Zip function in Python to change to a new character set Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd….xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : co 2 min read Map function and Lambda expression in Python to replace characters Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : str = 'grrksfoegrrks' c1 = e, c2 = r Output : geeksforgeeks Input : str = 'ratul' c1 = t, c2 = h Output : rahul We have an existing solution for this problem in C++. Please refer to Replace a character c1 with c2 and c2 with c1 in a string S. We can solve th 2 min read Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv 1 min read Intersection of two arrays in Python ( Lambda expression and filter function ) Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun 1 min read Prefix sum array in Python using accumulate function We are given an array, find prefix sums of given array. Examples: Input : arr = [1, 2, 3] Output : sum = [1, 3, 6] Input : arr = [4, 6, 12] Output : sum = [4, 10, 22] A prefix sum is a sequence of partial sums of a given sequence. For example, the cumulative sums of the sequence {a, b, c, ...} are a, a+b, a+b+c and so on. We can solve this problem 1 min read Python map function to find row with maximum number of 1's Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function 1 min read Intersection() function Python Python set intersection() method returns a new set with an element that is common to all set The intersection of two given sets is the largest set, which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. Python Set intersec 2 min read Python map function | Count total set bits in all numbers from 1 to n Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t 2 min read Union() function in Python Python set Union() Method returns a new set that contains all the items from the original set. The union of two given sets is the set that contains all the elements of both sets. The union of two given sets A and B is a set that consists of all the elements of A and all the elements of B such that no element is repeated. The symbol for denoting uni 3 min read Python | Permutation of a given string using inbuilt function A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA We have existing solution for this problem please refer Permutations of a given 2 min read sciPy stats.tsem() function | Python scipy.stats.tsem(array, limits=None, inclusive=(True, True)) calculates the trimmed standard error of the mean of array elements along the specified axis of the array. Its formula :- Parameters : array: Input array or object having the elements to calculate the trimmed standard error of the mean. axis: Axis along which the trimmed standard error of 2 min read Python | fsum() function fsum() is inbuilt function in Python, used to find sum between some range or an iterable. To use this function we need to import the math library. Syntax : maths.fsum( iterable ) Parameter : iterable : Here we pass some value which is iterable like arrays, list. Use : fsum() is used to find the sum of some range, array , list. Return Type : The fun 1 min read Python | cmp() function cmp() method in Python 2.x compares two integers and returns -1, 0, 1 according to comparison. cmp() does not work in python 3.x. You might want to see list comparison in Python. NoteThe cmp function was a built-in function in Python 2 for comparing the values of two objects. It has been removed in Python 3 and replaced with the == and is operators 2 min read Python math function | modf() modf() function is an inbuilt function in Python that returns the fractional and integer parts of the number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float. Syntax : modf(number) Time Complexity: O(1) Auxiliary Space: O(1) Parameter : There is only one mandatory parameter which is the numbe 3 min read Python math function | hypot() hypot() function is an inbuilt math function in Python that return the Euclidean norm, [Tex]\sqrt{(x*x + y*y)} [/Tex]. Syntax : hypot(x, y) Parameters : x and y are numerical values Returns : Returns a float value having Euclidean norm, sqrt(x*x + y*y). Error : When more than two arguments are passed, it returns a TypeError. Note : One has to impor 2 min read Python int() Function Python int() function returns an integer from a given object or converts a number in a given base to a decimal. Example: In this example, we passed a string as an argument to the int() function and printed it. C/C++ Code age = "21" print("age =", int(age)) Output: age = 21Python int() Function Syntax The syntax of the int() func 4 min read fromisoformat() Function Of Datetime.date Class In Python The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date 2 min read Article Tags :
  • Python
  • python
  • Python-Built-in-functions
Practice Tags :
  • python
  • python
Like three90RightbarBannerImg Explore More We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It ! Lightbox Improvement Suggest changes Suggest Changes Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal. geeksforgeeks-suggest-icon Create Improvement Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all. geeksforgeeks-improvement-icon Suggest Changes min 4 words, max CharLimit:2000

What kind of Experience do you want to share?

Interview Experiences Admission Experiences Career Journeys Work Experiences Campus Experiences Competitive Exam Experiences

Từ khóa » Hàm Ord