Встроенная функция Python chr() используется для преобразования целого числа в символ, а функция ord() используется для обратного, т. е. преобразования символа в целое число.
Давайте кратко рассмотрим обе эти функции и поймем, как их можно использовать.
Функция chr()
Принимает целое число i и преобразует его в символ c , поэтому возвращает строку символов.
Вот пример, демонстрирующий то же самое:
# Convert integer 65 to ASCII Character ('A') y = chr(65) print(type(y), y) # Print A-Z for i in range(65, 65+25): print(chr(i), end = " , ")
A A , B , C , D , E , F , G , H , I , J , K , L , M , N , O , P , Q , R , S , T , U , V , W , X , Y , Z
Допустимый диапазон для аргумента — от 0 до 1,114 111 (0x10FFFF в шестнадцатеричном формате). ValueError будет ValueError , если целое число i находится за пределами этого диапазона.
Давайте проверим это на некоторых примерах
ValueError: chr() arg not in range(0x110000)
start = 0 end = 1114111 try: for i in range(start, end+2): a = chr(i) except ValueError: print("ValueError for i adfox_160258816397671781">
ValueError for i = 1114112
Функция ord()
Функция ord() принимает строковый аргумент из одного символа Юникода и возвращает его целочисленное значение кодовой точки Юникода. Делает наоборот chr() .
Принимает один символ Юникода (строка длиной 1) и возвращает целое число, поэтому формат следующий:
Чтобы убедиться, что он работает наоборот, чем chr() , давайте протестируем функцию на нескольких примерах.
# Convert ASCII Unicode Character 'A' to 65 y = ord('A') print(type(y), y) alphabet_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Print 65-90 for i in alphabet_list: print(ord(i), end = " , ")
Мы передаем целое число 18 в шестнадцатеричном формате в chr() , которая возвращает шестнадцатеричное значение 0x12 . Мы передаем это в chr() и используем ord() чтобы вернуть наше целое число.
Обратите внимание, что мы также можем получить целое число с помощью int() , поскольку односимвольная строка также является строкой, которая может быть допустимым параметром для указанной выше функции.
I'm working on making a URL shortener for my site, and my current plan (I'm open to suggestions) is to use a node ID to generate the shortened URL. So, in theory, node 26 might be short.com/z , node 1 might be short.com/a , node 52 might be short.com/Z , and node 104 might be short.com/ZZ . When a user goes to that URL, I need to reverse the process (obviously). I can think of some kludgy ways to go about this, but I'm guessing there are better ones. Any suggestions?
6 Answers 6
chr words in the range of the ascii characters (0 - 255), however, unichr works for the unicode character set.
If multiple characters are bound inside a single integer/long, as was my issue:
s = '0123456789' nchars = len(s) # string to int or long. Type depends on nchars x = sum(ord(s[byte])>8*(nchars-byte-1))&0xFF) for byte in range(nchars))
Yields '0123456789' and x = 227581098929683594426425L
Thanks for asking. I'll grant it's slightly off of the use case in the OP, given that base64 or base58 encoding would be most applicable. I had arrived on this question based on the title, literally converting an integer to ascii text as if the integer has ascii encoded data embedded in its bytes. I posted this answer in the event others arrived here with the same desired outcome.
What about BASE58 encoding the URL? Like for example flickr does.
# note the missing lowercase L and the zero etc. BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' url = '' while node_id >= 58: div, mod = divmod(node_id, 58) url = BASE58[mod] + url node_id = int(div) return 'http://short.com/%s' % BASE58[node_id] + url
Turning that back into a number isn't a big deal either.
This is great. I ended up finding another (more complete) answer here on SO though: stackoverflow.com/questions/1119722/…
Use hex(id)[2:] and int(urlpart, 16) . There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.
Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode and b32decode . You should give True for both the casefold and map01 options to b32decode in case people write down your shortened URLs.
Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. 🙂
In this tutorial, we will look at how to convert an integer to a char in Python with the help of some examples. We’ll be looking at use-cases of finding the char (string) representing a character whose Unicode point is the integer.
How to convert integer to char in Python?
You can use the Python built-in chr() function to get the character represented by a particular integer in Unicode. The following is the syntax –
Pass the integer as an argument. The valid range for the integer argument is from 0 through 1,114,111 (0x10FFFF in base 16). If you pass an integer outside of this range, it will result in a ValueError .
Examples
Let’s look at some examples of using the above syntax –
Get the character represented by a number in Unicode
Let’s pass the integer 65 to the chr() function.
# integer to char ch = chr(65) # display char and its type print(ch) print(type(ch))
We get 'A' from the function. The number 65 points to the character 'A' in Unicode.
Let’s look at another example.
# integer to char ch = chr(44) # display char and its type print(ch) print(type(ch))
We get the comma character, ',' for the integer 44.
You can use the Python built-in ord() function to get the corresponding integer for a character in Unicode.
# char to integer print(ord('A')) print(ord(','))
We get 65 for the character ‘A’ and 26 for the character ‘$’.
What if you pass a negative integer to the above function?
Let’s pass a negative integer to the chr() function as an argument.
# integer to char ch = chr(-65) # display char and its type print(ch) print(type(ch))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [20], in 1 # integer to char ----> 2 ch = chr(-65) 3 # display char and its type 4 print(ch) ValueError: chr() arg not in range(0x110000)
We get a ValueError . This is because the passed integer is outside the valid range of 0 through 1,114,111.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials. We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.
Career Guides
Start Your Path -
Data Scientist
Data Analyst
Data Engineer
Machine Learning Engineer
Statistician
Data Architect
Software Developer
Useful Resources
This website uses cookies to improve your experience. We'll assume you're okay with this, but you can opt-out if you wish.
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
To convertint to char in Python, you can use the “chr()” method. For example, the “ chr(97)” expression returns “a”. The chr() method returns a character (a string) from an integer (it represents the Unicode code point of the character).
Syntax
Parameters
i: The chr() method takes a single parameter which is an integer.
Return Value
The chr() function returns a character (a string) whose Unicode code point is the integer.
Example 1: How to Use chr() method
Let’s use the chr() function to convert int to a character.
print(chr(97))print(chr(65))print(chr(1100))
And we get the characters in the output concerning its ASCII value. For example, the chr() method returns a character whose Unicode point is num, an integer.
Example 2: Integer passed to chr() is out of the range
If we pass the negative value to the chr() function, then it returns ValueError: chr() arg not in range(0x110000).
Traceback (most recent call last):File "/Users/krunal/Desktop/code/pyt/database/app.py", line 7, in print(chr(-1))ValueError: chr() arg not in range(0x110000)
We have passed an integer outside the range, and then the method returns a ValueError.
Example 3: Convert a list of integers to characters
To create a list in Python, you can use the [ ] and add the values inside it.
listA = [69, 72, 78, 81, 90, 99]for number in listA:char = chr(number)print("Character of ASCII value", number, "is ", char)
Character of ASCII value 69 is ECharacter of ASCII value 72 is HCharacter of ASCII value 78 is NCharacter of ASCII value 81 is QCharacter of ASCII value 90 is ZCharacter of ASCII value 99 is c