First example. To begin we use the count method several times on a string containing the text "Plutarch." We count the letter "a," which occurs only once.
Then We count the letters "a" and "r," and finally we count a range of 3 letters.
Tip We can use a range of characters within the argument to count: "a-c" means "abc."
value = "Plutarch"# The letter "a" occurs once.
a = value.count"a"
# The letters "a" and "r" occur twice in total.
b = value.count"ar"
# Letters in range "a" through "c" occur twice in total.
c = value.count"a-c"
Letter, digit ranges. Here are more examples for ranges. We invoke count() twice here to count all letters (lower and upper) and all digits (0 through 9).
Detail We can count all lowercase and all uppercase letters—this results in the total letter count.
Detail We can count all digits by using the string "0-9," which covers all possible digits.
# Part A: count all ASCII lowercase and uppercase letters.
value = "Bird?!"
result1 = value.count("a-zA-Z")
# Part B: count all digits.
value2 = "cat57"
result2 = value2.count("0-9")
Metacharacter issue. We cannot pass a regexp metacharacter to the count method. It will not match "word" characters with the metacharacter "\w" and instead counts the letters directly.
value = "word"# We cannot use this metacharacter to mean "word characters."# ... It matches "w" so returns 1, not 4.
A review. We invoked the count method on strings to count certain letters and ranges of letters and digits. This method can replace some loops (or iterator calls to each_char).