Trusted answers to developer questions

What is the punctuation constant in Python?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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 string
punctuation_output = string.punctuation
print("string.punctuation = '%s'" % (punctuation_output))

Explanation

  • 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.

Example 2

import string
def has_punctuation(str_input):
for i in str_input:
if i in string.punctuation:
return True
return False
str_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 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.

RELATED TAGS

python
Did you find this helpful?