The chr()
and ord()
methods in Python are used to convert between characters and their corresponding ASCII or Unicode values. Here’s a detailed explanation and some examples to illustrate how they work.
chr()
The chr()
function returns the string representing a character whose Unicode code point is the integer passed as an argument. For ASCII values, this ranges from 0 to 127.
Syntax:
chr(i)
i
: An integer representing a Unicode code point.
Examples:
print(chr(65)) # Output: 'A'
print(chr(97)) # Output: 'a'
print(chr(8364)) # Output: '€' (Euro sign)
ord()
The ord()
function returns an integer representing the Unicode code point of the given Unicode character.
Syntax:
ord(c)
c
: A single Unicode character.
Examples:
print(ord('A')) # Output: 65
print(ord('a')) # Output: 97
print(ord('€')) # Output: 8364
Combining chr()
and ord()
You can use chr()
and ord()
together to encode and decode characters.
Example:
char = 'G'
encoded = ord(char)
decoded = chr(encoded)
print(f"Character: {char}, Encoded: {encoded}, Decoded: {decoded}")
# Output: Character: G, Encoded: 71, Decoded: G
Practical Examples
Printing Characters in a Sequence
You can use a loop to print a sequence of characters.
Example:
# Print uppercase A to Z
for i in range(65, 91):
print(chr(i), end=' ')
# Output: 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
Creating a String of Incremental Characters
You can create a string by accumulating characters in a loop.
Example:
str1 = ""
for i in range(4):
str1 += chr(65 + i)
print(str1)
# Output:
# A
# AB
# ABC
# ABCD
Reversing a String
You can reverse the process by printing progressively shorter substrings.
Example:
str1 = "ABCD"
for i in range(len(str1)):
print(str1[:len(str1) - i])
# Output:
# ABCD
# ABC
# AB
# A
Unicode Characters
Both chr()
and ord()
work with Unicode, which allows for a vast range of characters beyond ASCII.
Example:
print(chr(128512)) # Output: '😀' (Grinning Face emoji)
print(ord('😀')) # Output: 128512
Application in Data Processing
The chr()
and ord()
functions can be useful in various scenarios, such as:
Generating sequences of characters programmatically.
Encoding and decoding messages.
Working with character data in encryption and compression algorithms.
String Methods Overview
Case Conversion Methods
str.upper()
str.lower()
str.capitalize()
str.title()
str.swapcase()
Whitespace Removal Methods
str.strip()
str.lstrip()
str.rstrip()
Search and Check Methods
str.startswith()
str.endswith()
str.find()
str.index()
str.rfind()
str.rindex()
Content Test Methods
str.isupper()
str.islower()
str.isalpha()
str.isdigit()
str.isalnum()
str.isspace()
str.istitle()
str.isidentifier()
str.isprintable()
String Modification Methods
str.replace()
str.split()
str.join()
str.partition()
str.ljust()
str.rjust()
str.zfill()
Additional Methods
str.casefold()
str.splitlines()
Detailed Examples
1. Case Conversion Methods
str.upper()
: Converts all characters to uppercase.
print("hello".upper()) # Output: 'HELLO'
str.lower()
: Converts all characters to lowercase.
print("HELLO".lower()) # Output: 'hello'
str.capitalize()
: Capitalizes the first character and lowercases the rest.
print("hello world".capitalize()) # Output: 'Hello world'
str.title()
: Capitalizes the first character of each word.
print("hello world".title()) # Output: 'Hello World'
str.swapcase()
: Swaps the case of each character.
print("Hello World".swapcase()) # Output: 'hELLO wORLD'
2. Whitespace Removal Methods
str.strip()
: Removes leading and trailing whitespace.
print(" hello ".strip()) # Output: 'hello'
str.lstrip()
: Removes leading whitespace.
print(" hello ".lstrip()) # Output: 'hello '
str.rstrip()
: Removes trailing whitespace.
print(" hello ".rstrip()) # Output: ' hello'
3. Search and Check Methods
str.startswith()
: Checks if the string starts with the specified substring.
print("hello world".startswith("hello")) # Output: True
str.endswith()
: Checks if the string ends with the specified substring.
print("hello world".endswith("world")) # Output: True
str.find()
: Returns the lowest index of the substring if found, otherwise -1.
print("hello world".find("world")) # Output: 6
str.index()
: Returns the lowest index of the substring if found, otherwise raises a ValueError.
print("hello world".index("world")) # Output: 6
str.rfind()
: Returns the highest index of the substring if found, otherwise -1.
print("hello world hello".rfind("hello")) # Output: 12
str.rindex()
: Returns the highest index of the substring if found, otherwise raises a ValueError.
print("hello world hello".rindex("hello")) # Output: 12
4. Content Test Methods
str.isupper()
: Checks if all characters are uppercase.
print("HELLO".isupper()) # Output: True
str.islower()
: Checks if all characters are lowercase.
print("hello".islower()) # Output: True
str.isalpha()
: Checks if all characters are alphabetic.
print("hello".islower()) # Output: True
str.isdigit()
: Checks if all characters are digits.
print("12345".isdigit()) # Output: True
str.isalnum()
: Checks if all characters are alphanumeric.
print("hello123".isalnum()) # Output: True
str.isspace()
: Checks if all characters are whitespace.
print(" ".isspace()) # Output: True
str.istitle()
: Checks if each word is capitalized.
print("Hello World".istitle()) # Output: True
str.isidentifier()
: Checks if the string is a valid identifier.
print("variable_name".isidentifier()) # Output: True
str.isprintable()
: Checks if all characters are printable.
print("Hello World!".isprintable()) # Output: True
5. String Modification Methods
str.replace()
: Replaces occurrences of a substring with another substring.
print("hello world".replace("world", "Python")) # Output: 'hello Python'
str.split()
: Splits the string into a list of substrings.
print("hello world".split()) # Output: ['hello', 'world']
str.join()
: Joins elements of an iterable with the string as a separator.
print(", ".join(["apple", "banana", "cherry"])) # Output: 'apple, banana, cherry'
str.partition()
: Splits the string at the first occurrence of the separator into a tuple.
print("hello world".partition(" ")) # Output: ('hello', ' ', 'world')
str.center
()
: Centers the string with specified width and fill character.
print("hello".center(10, '-')) # Output: '--hello---'
str.ljust()
: Left-justifies the string with specified width and fill character.
print("hello".ljust(10, '-')) # Output: 'hello-----'
str.rjust()
: Right-justifies the string with specified width and fill character.
print("hello".rjust(10, '-')) # Output: '-----hello'
str.zfill()
: Pads the string on the left with zeros to fill the specified width.
print("42".zfill(5)) # Output: '00042'
6. Additional Methods
str.casefold()
: Converts the string to lowercase in a way that is aggressive and suitable for caseless comparisons.
print("Groß".casefold()) # Output: 'gross'
str.splitlines()
: Splits the string at line breaks and returns a list of lines.
print("first line\nsecond line\nthird line".splitlines()) # Output: ['first line'