HomeSearch

Python ascii Example

This Python page uses ascii, ascii_lowercase and ascii_uppercase. It covers whitespace and digits.
ASCII. Most common English letters are ASCII—the lowercase "a," the uppercase Z, the digit 0. With ascii we change text encoding.
An 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.

Python program that uses ascii built-in # This string contains an umlaut. value = "Düsseldorf" print(value) # Display letter with escaped umlaut. print(ascii(value)) Output 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.

Python program that uses ascii_letters constant import string # The letters constant is equal to lowercase + uppercase. print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) Output 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.
Python program that uses string.digits import string # Loop over digits using string.digits constant. for digit in string.digits: print(digit) Output 0 1 2 3 4 5 6 7 8 9
Punctuation. Another important category of ASCII characters is punctuation characters like commas and quotes. We can also use string.whitespace.string.punctuation
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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls