ASCII. Most common English letters are ASCII—the lowercase "a," the uppercase Z, the digit 0. With ascii we change text encoding.
Punctuation. Another important category of ASCII characters is punctuation characters like commas and quotes. We can also use string.whitespace.
First example. For many English programs, the ASCII character set is sufficient. No letters with accents occur. But sometimes Unicode is needed.
Info With ascii, a built-in, we escape Unicode characters into ASCII characters.
# This string contains an umlaut.
value = "Düsseldorf"
print(value)
# Display letter with escaped umlaut.
print(ascii(value))Düsseldorf
'D\xfcsseldorf'
Ascii_letters, lowercase, uppercase. The string module contains helpful constants. We can use these to loop over all lowercase or uppercase ASCII letters, or to build translation tables.
Tip We import the string module and access these constants on it. This is an easy to way to access the constants.
import string
# The letters constant is equal to lowercase + uppercase.
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
String.digits. This is another constant in the string module. If you ever need to loop over the strings "0" through "9" this is an option. The code is clean and simple.
import string
# Loop over digits using string.digits constant.
for digit in string.digits:
print(digit)0
1
2
3
4
5
6
7
8
9
A summary. We can access constant strings like string.ascii_letters to get ascii values. To change text encoding we can use the ascii built-in.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 25, 2022 (edit).