Home Python Course Menu Book

Python len, Python count


The Python len function

You'll often need to know how many characters a word has. For example, you want to loop round all the characters in a string of text, from zero to however many characters the string has. In which case, you can use the len() function:

myText = "supercalifragilisticexpialidocious"
textLength = len(myText)
print("Character count is:", textLength)

Notice that the len() function is not used with a dot, but just by itself. The text whose length you want to check goes between round brackets. You'll then get back a number, which you can do something with.


The Python count function

If you need to count how many times a single character, or a string of text, appears in another string of text, you can use the count() function.

myText = "Love, love, love - love is all you need."
wordcount = myText.count("love")

If you run the above code, the output window will display a figure of 3, meaning it has found love three times. It didn't count the first love because that has a capital letter. In between the round brackets of count(), we had all lowercase letters.


In the next lesson, you'll learn how to deal with white space in Python.