What is the printable constant in Python?
The string module
In Python, string is a built-in module. It is a collection of different constants and classes for working with strings. This module has to be imported before use.
The printable constant
The printable constant in the string module contains the ASCII characters which are considered printable as a string.
The value of the constant is as follows:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
The value of the constant is a string consisting of the following constants:
The string constants above are considered printable. Hence, the printable constant consists of the above constants combined together as a string.
Syntax
string.printable
We can access the printable constant via the string module.
Example 1
import stringprintable_output = string.printableprint("string.printable = '%s'" % (printable_output))
Explanation
-
Line 1: We import the
stringmodule. -
Line 3: We store the output of
string.printablein the variableprintable_output. -
Line 5: We print the variable
printable_output.
Example 2
import stringdef all_chars_printable(str_input):for i in str_input:if i not in string.printable:return Falsereturn Truestr_to_check_1 = "abjiaosfÇ"print("Is %s printable? %s" % (str_to_check_1, all_chars_printable(str_to_check_1)))str_to_check_2 = "abji232daosfdgf()#$#RFDFD"print("Is %s printable? %s" % (str_to_check_2, all_chars_printable(str_to_check_2)))
Explanation
-
Line 1: We import the
stringmodule. -
Lines 3–9: We define a function called
all_chars_printablethat accepts a string as its parameter and checks whether this string contains only printable characters. -
Line 11: We define a string called
str_to_check_1that contains ASCII and Unicode characters. -
Line 12: We invoke the
all_chars_printablefunction by passingstr_to_check_1as the parameter. The function returnsFalseindicating thatstr_to_check_1consists of non-printable characters, meaning the characters not present in thestring.printableconstant. -
Line 14: We define a string called
str_to_check_2that contains only ASCII characters. -
Line 15: We invoke the
all_chars_printablefunction passingstr_to_check_2as the parameter. The function returnsTrueindicating thatstr_to_check_2consists of printable characters only, meaning the characters present in thestring.printableconstant.