How to Count Punctuation in Python

In this tutorial, you will learn how to count punctuation marks in Python. For this purpose, we will get help from Python’s built-in module string. Don’t worry if you are a beginner, we’ve got you covered every step of the way.

Step 1: Understanding Python’s Built-in String Module

The string module is one of Python’s built-in modules that provides various string manipulation functions and constants.

Among these constants is string.punctuation which contains all the common punctuation marks. Understand more about this module at Python’s official documentation here.

Step 2: Create a string of text for counting punctuation

For the purpose of this tutorial, we will create a sample text that includes punctuation marks. Later, we will use this text to count the punctuation marks.

Step 3: Counting the punctuation marks

Now, we will write our Python script to count the punctuation marks in the created text. Here is the breakdown of our script:

1. Import the string module.
2. Initialize a count variable to zero – this variable will hold the total count of punctuation marks.
3. Loop through each character in the text. If the character is a punctuation, increment the count variable by one.

Here is our Python script:

Output

Total punctuation marks: 8

Full Python code

Total punctuation marks:  8

Conclusion

Mastering the string module is essential in Python especially when dealing with text manipulation tasks. Today, you’ve learned how to count punctuation symbols in a given text using Python and now you are one step closer to becoming a Python expert. Keep practicing!