Tip 27 Discover All Characters in One Place

Pythonic Programming — by Dmitry Zinoviev (36 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Transpose with zip() | TOC | glob() the Files 👉

★2.7, 3.4+ Sometimes, you need to check whether a character belongs to one of the character classes, such as letters, digits, white spaces, and the like. You could exercise your brain and try to remember all English letters (or some obscure printable characters), but why, if Python comes with the module string? The module is very compact and provides nine strings that contain characters by class:

​ string.ascii_letters​=> ​'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'​​ string.ascii_lowercase​=> ​'abcdefghijklmnopqrstuvwxyz'​​ string.ascii_uppercase​=> ​'ABCDEFGHIJKLMNOPQRSTUVWXYZ'​​ string.digits​=> ​'0123456789'​​ string.hexdigits​=> ​'0123456789abcdefABCDEF'​​ string.octdigits​=> ​'01234567'​​ string.printable​=> ​'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()​
​=> ​*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'​
​ string.punctuation​=> ​'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'​​ string.whitespace

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.