Python Arena
Step 3 of 5

count, index and replace

Strings and lists have more methods worth knowing. count tells how many times something appears. It works on strings, where it counts a piece of text, and on lists, where it counts an item:

text = "this list has six items"
print(text.count("s"))
print(text.count("is"))
numbers = [3, 1, 3, 3, 2]
print(numbers.count(3))
print("banana".count("ana"))
Output
5
2
3
1

The last line needs a closer look. ana starts at index 1 of banana and again at index 3, but the two share the a in the middle. count doesn't count pieces that overlap: once it has found one, it goes on looking only after its end, so it finds just one.

Where is it?

index returns the index of the first place where something is found, in a string or in a list:

names = ["Ada", "Linus", "Grace"]
print(names.index("Grace"))
print("banana".index("an"))
print(names.index("Guido"))
Output
2
1
Python stops with
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(names.index("Guido"))
          ~~~~~~~~~~~^^^^^^^^^
ValueError: list.index(x): x not in list

If the item isn't there, index stops the program, so check with in first. For strings, you also know find, which returns -1 instead of stopping.

Replacing

replace returns a new string where every appearance of one piece of text is replaced with another:

text = "I like cats. Cats like me."
print(text.replace("like", "love"))
print(text.replace("cat", "dog"))
print(text)
Output
I love cats. Cats love me.
I like dogs. Cats like me.
I like cats. Cats like me.

It replaces every appearance, not just the first. Capital letters count: "Cats" isn't "cat", so it stays. And since strings can't be changed, text itself stays as it was. Forgetting that is the most common replace bug:

text = "Hello, World"
text.replace("World", "Python")
print(text)
text = text.replace("World", "Python")
print(text)
Output
Hello, World
Hello, Python

The first replace makes the new string and throws it away. Only when the result is stored does text say Hello, Python.

Replacing with the empty string "" removes a piece of text: "1,000,000".replace(",", "") is "1000000".

Your task

Challenge 1 of 3

Fill in the blanks so the program counts the letter e in the text and then replaces every cat with dog:

Letter e: 4
the dog sees the dog

Challenge 2

Write the function censor(text: str, banned: list) -> str, which returns the text with every banned word replaced by stars, one star per letter. For example, censor("you silly goose", ["silly"]) returns 'you ***** goose'.

Challenge 3

Write a program that asks for a text and a piece of text to look for. It prints how many times the piece is in the text and the index where it's first found. If it isn't found at all, it prints Not found:

Text: the cat sat on the mat
Find: at
Found 3 times, first at index 5