To count how many times a substring appears in a Python string, use the built-in str.count() method: text.count(substring). It returns an integer and is case-sensitive. For example, "banana".count("an") returns 2. That is the short answer; the rest of this guide explains the optional start and end arguments, the edge cases that trip people up, and how to count safely when the text is messy.
What You'll Need
- Python 3 installed on your computer (any recent 3.x version is fine). You can check by running
python --versionorpython3 --versionin a terminal or command prompt. - A way to run Python code: the interactive interpreter, IDLE, VS Code, PyCharm, or an online Python playground.
- Optional: a text file or string you want to analyze, such as a log line, a paragraph, or a CSV field.
Step-by-Step
- Open a Python session. Run
python(orpython3) in your terminal, or open a new file in your editor. The interactive interpreter is the fastest way to try examples. - Create the string you want to search. Assign it to a variable so you can reuse it:
text = "the cat sat on the mat". Strings can be single-quoted, double-quoted, or triple-quoted for multi-line text. - Call
.count()with the substring. Typetext.count("at")and press Enter. Python returns3because "at" appears in "cat", "sat", and "mat". The method does not modify the original string; it only returns a number. - Understand case sensitivity.
"Cat".count("cat")returns0. If you want a case-insensitive count, convert both sides first:text.lower().count("cat"). This is the most common fix for unexpected zero results. - Use the optional start argument.
text.count("at", 5)starts counting from index 5 (the sixth character). This is useful when you want to ignore a header or a prefix. Indexes are zero-based, so index 0 is the first character. - Use the optional end argument.
text.count("at", 0, 10)counts only within the slice from index 0 up to but not including index 10. The end index is exclusive, exactly like slicing. If you omit start, you must still pass a start value to use end, for exampletext.count("at", 0, 10). - Count overlapping occurrences if needed.
.count()finds non-overlapping matches."aaaa".count("aa")returns2, not3. To count overlaps, use a loop or a regular expression with a lookahead:import re; len(re.findall(r"(?=aa)", "aaaa"))returns3. Only reach for this when the distinction matters. - Count a single character. The same method works:
text.count("a"). For counting every character at once, usecollections.Counter(text), which returns a dictionary-like object of frequencies. That is a different tool, but it is the right one when you need a full histogram. - Count in a file. Read the file into a string first:
with open("log.txt", encoding="utf-8") as f: data = f.read(), then calldata.count("ERROR"). Always specify an encoding to avoid platform-dependent decoding surprises. - Check your result. Print the count and a small sample of the text around a match to confirm you are counting what you think you are. A quick sanity check prevents most reporting errors.
Common Mistakes
- Forgetting case sensitivity. Searching for "Error" in text that contains "error" returns zero. Normalize case with
.lower()or.casefold()before counting. - Expecting overlapping matches. As shown above,
.count()does not overlap. If your data has repeated patterns like "aaa", decide whether overlaps should count and use a regex lookahead if they should. - Mixing up the end index. The end argument is exclusive.
text.count("at", 0, 4)does not include index 4. Off-by-one errors here produce counts that look almost right. - Passing the wrong argument order. The signature is
count(sub[, start[, end]]). Passing end without start is not allowed; use0as the start. - Counting on bytes versus strings. If you read a file in binary mode, you get
bytes, and you must pass a bytes substring such asb"ERROR". Mixingstrandbytesraises aTypeError. - Assuming
.count()works on lists. Lists have their own.count(), but it counts whole elements, not substrings. For lists of strings, join first or loop.
Tips
- Use
.casefold()instead of.lower()when working with non-English text, because it handles more Unicode cases correctly. - Strip whitespace before counting tokens:
text.strip().count("word")avoids leading and trailing space issues in some comparisons. - For word counts, split first:
len(text.split())counts words, whiletext.count("word")counts substring occurrences, which can match inside other words. - When counting multiple substrings, store them in a list and loop, or use a dictionary comprehension for readability.
- Remember that
.count()returns0for an empty substring search? Actually,"abc".count("")returns4(length plus one), which surprises many people. Avoid empty substrings unless you specifically want that behavior.
Troubleshooting
- You get
AttributeError: 'int' object has no attribute 'count'. You are calling.count()on a number, not a string. Convert withstr(value)first. - You get
TypeError: must be str, not int. The substring argument must be a string. Wrap numbers in quotes or convert them. - The count is zero but you can see the text. Check for hidden characters, different Unicode forms (for example curly versus straight apostrophes), or case differences. Print
repr(text)to reveal what is actually there. - The count seems too low. You may be hitting the non-overlapping rule, or your start/end slice is cutting off part of the string. Remove the optional arguments and recount to isolate the cause.
- Counting in a file gives odd results. Confirm you opened it in text mode with the correct encoding, and that you read the whole file rather than one line.
Frequently Asked Questions
Does str.count() modify the original string?
No. Strings are immutable in Python, and .count() only returns an integer. The original variable is unchanged.
How do I count case-insensitively?
Convert the string and the substring to the same case first, for example text.lower().count("error"). For broader Unicode support, use .casefold().
Can I count overlapping occurrences with .count()?
No. .count() finds non-overlapping matches. Use re.findall with a lookahead pattern if overlaps must be included.
What does "abc".count("") return?
It returns 4, which is the string length plus one. This is documented behavior for empty substrings and is rarely what you want.
Is .count() fast enough for large files?
It is implemented in C and is generally efficient for substring counting. For very large files, read in chunks or use a streaming approach if memory is a concern.
How is .count() different from len()?
len(text) returns the number of characters. text.count(sub) returns how many times a substring appears. They answer different questions.