What is the punctuation constant in Python?
The string module
The string module is a built-in module in Python. It’s a collection of different constants and classes used for working with strings.
The punctuation constant
The punctuation constant in the string module contains the string of ASCII characters considered to be punctuation characters in the C locale.
The value of the constant is as follows:
!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~
Syntax
string.punctuation
As punctuation is a constant, we can access it via the string module.
Let’s look at two code examples that use the punctuation constant.
Example 1
import stringpunctuation_output = string.punctuationprint("string.punctuation = '%s'" % (punctuation_output))
Explanation
-
Line 1: We import the
stringmodule. -
Line 3: We store the output of
string.punctuationin thepunctuation_outputvariable. -
Line 5: We print the
punctuation_outputvariable.
Example 2
import stringdef has_punctuation(str_input):for i in str_input:if i in string.punctuation:return Truereturn Falsestr_to_check_1 = "abjiaosfdgfRFDFD"print("Does %s contain any punctuation? %s" % (str_to_check_1, has_punctuation(str_to_check_1)))str_to_check_2 = "abji232daosfdgfRFDFD*&^\""print("Does %s contain any punctuation? %s" % (str_to_check_2, has_punctuation(str_to_check_2)))
Explanation
-
Line 1: We import the
stringmodule. -
Lines 3–9: We define a function called
has_punctuationthat accepts a string as its parameter. It also checks whether it contains any punctuation characters. It returnsTrueif the string has the punctuation characters and returnsFalseif it doesn’t. -
Line 11: We define a string called
str_to_check_1that contains no punctuation. -
Line 12: We invoke the
has_punctuationfunction by passingstr_to_check_1as the parameter. -
Line 14: We define a string called
str_to_check_2that contains punctuations. -
Line 15: The
has_punctuationfunction is invoked passingstr_to_check_2as the parameter.