Python chr()
: Convert Integer to Character
Ever needed to convert a number into a letter? That’s where chr()
comes in handy!
print(chr(65)) # Output: 'A'
print(chr(97)) # Output: 'a'
Simple, right? Just pass an ASCII or Unicode number, and chr()
gives you the character!
Syntax
chr(number)
- number → An integer representing an ASCII or Unicode code point.
- Returns → The corresponding character.
1. Generating an Alphabet Dynamically
Instead of hardcoding letters, use chr()
to generate the alphabet dynamically.
alphabet = [chr(i) for i in range(65, 91)] # A-Z
print(alphabet)
Great for automation, pattern generation, and text-based applications!
2. Converting Unicode Code Points to Characters
Need to handle special characters or emojis? chr()
works beyond ASCII!
print(chr(8364)) # Output: '€' (Euro symbol)
print(chr(128512)) # Output: '😀' (Smiley emoji)
Useful for internationalization, emoji processing, and modern app development.
3. Using chr()
with SQL & Data Processing
Sometimes, databases store numeric ASCII codes instead of actual characters. Use chr()
to convert them back.
ascii_code = 67 # 'C' in ASCII
print(f"SELECT * FROM users WHERE name LIKE '{chr(ascii_code)}%';")
Handy when dealing with legacy databases or raw data processing!
Key Notes
- ✔ Converts numbers to characters – useful for encoding &