Count characters and strings in Python

Authors

To count the number of characters in a string in Python, you can use the len() function.

This function returns the number of characters in a string, including spaces and special characters.

For example:

string = "Hello World"
count = len(string)
print(count)
# Output: 11

To count the number of occurrences of a specific substring in a string, you can use the count() method.

This method returns the number of times a substring appears in a string.

For example:

string = "Hello World"
count = string.count("l")
print(count)
# Output: 3

In the examples above, the len() function is used to count the number of characters in a string, and the count() method is used to count the number of occurrences of a substring in a string.

TrackingJoy