Often in programming and data analysis, we need to count how many times a word appears in a string or text. Python, a free and open-source programming language, offers a simple way to achieve this. In this tutorial, we’ll guide you on how to count how many times a specific word appears in a string in Python.
Step 1: Define the string
To start with, you need to define the string on which you want to conduct the word count. In Python, strings are defined by enclosing characters in quotes. You can use either single, double, or triple quotes to define a string.
1 |
text = 'Python is simple. Python is friendly. Python is open source.' |
Step 2: Use the count method
Python has a built-in method called count() that can be used to count how many times a word appears in a string. You just need to call this method on the string and pass the word you want to count as an argument.
1 |
count = text.count('Python') |
Step 3: Print the result
Now, you can print the result to the console using the print() function.
1 |
print('Python:', count) |
This will display the number of times ‘Python’ appears in the string.
Full code:
1 2 3 |
text = 'Python is simple. Python is friendly. Python is open source.' count = text.count('Python') print('Python:', count) |
Output:
1 |
Python: 3 |
Conclusion
In conclusion, Python makes it straightforward to count the occurrences of a word in a string. This can be achieved by using the built-in count() method. This method is quite useful when dealing with text data in fields like data analysis and natural language processing.