How to count a word in string Python

How to count a word in string Python

Python Tutorial

In certain applications, you may need to count a word in a string. In Python language supports to do that. To manipulate such strings is very easy to do using python.

For example there is a string like this:

x = "He is a good boy. I often see the boy helping his mother"

We want to know how many “He” words are in Python, so the result is:

number of He in the text is 1

To do that, there is one method we can use which is count().

Syntax:

string.count(value, start, end)

Exp:

value is a String (required) and case sensitive
start is as Integer (optional). This is used for position to start the search and default is 0
end as Integer (optional). his is used for position to end the search and default is the end of the string

First example

Now to be able to understand about this, we use directly the method in the code below:

x = "He is a good boy. I often see the boy helping his mother"
y = "He"

z = x.count(y)

print("Number of " + y + " in the text is " + str(z))

The result is :

number of He in the text is 1

The result is 1. It’s in the “He is a good boy”.

Second Example

The count() method is case sensitive. So the Python will see and look for word according to what we write.

I will change the word “He” to “he”, consider the following example:

x = "He is a good boy. I often see the boy helping his mother"
y = "he"

z = x.count(y)

print("Number of " + y + " in the text is " + str(z))

The result is:

Number of he in the text is 3

The result is 3, each of the, helping and mother.

Third example

And now, we will use the start position parameters to restrict Python from reading the string.

For example is:

x = "He is a good boy. I often see the boy helping his mother"
y = "he"

z = x.count(y, 32)

print("Number of " + y + " in the text is " + str(z))

The result is:

Number of he in the text is 2

The result is 2, each of helping and mother.

Fourth example

Now we specify the maximum position that Python wants to read. For example below:

x = "He is a good boy. I often see the boy helping his mother"
y = "he"

z = x.count(y, 32, 50)

print("Number of " + y + " in the text is " + str(z))

The result is:

Number of he in the text is 1

The result is 1, helping.

I hope this count word in string Python article can add to your insight into programming.

READ NEXT

Similar Posts