string
moduleThe string
module is a built-in module in Python. It’s a collection of different constants and classes used for working with strings.
punctuation
constantThe 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:
!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~
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.
import stringpunctuation_output = string.punctuationprint("string.punctuation = '%s'" % (punctuation_output))
Line 1: We import the string
module.
Line 3: We store the output of string.punctuation
in the punctuation_output
variable.
Line 5: We print the punctuation_output
variable.
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)))
Line 1: We import the string
module.
Lines 3–9: We define a function called has_punctuation
that accepts a string as its parameter. It also checks whether it contains any punctuation characters. It returns True
if the string has the punctuation characters and returns False
if it doesn’t.
Line 11: We define a string called str_to_check_1
that contains no punctuation.
Line 12: We invoke the has_punctuation
function by passing str_to_check_1
as the parameter.
Line 14: We define a string called str_to_check_2
that contains punctuations.
Line 15: The has_punctuation
function is invoked passing str_to_check_2
as the parameter.