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.
1 2 |
# sample text text = "Hello, world! How's it going? I'm learning Python. It's fun!" |
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:
1 2 3 4 5 6 7 8 9 10 11 |
import string # count initilization count = 0 # checking each character for char in text: if char in string.punctuation: count += 1 print("Total punctuation marks: ", count) |
Output
Total punctuation marks: 8
Full Python code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import string # sample text text = "Hello, world! How's it going? I'm learning Python. It's fun!" # count initilization count = 0 # checking each character for char in text: if char in string.punctuation: count += 1 print("Total punctuation marks: ", count) |
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!