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"))
5
2
3
1The 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"))
2
1Traceback (most recent call last):
File "main.py", line 4, in <module>
print(names.index("Guido"))
~~~~~~~~~~~^^^^^^^^^
ValueError: list.index(x): x not in listIf 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)
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)
Hello, World
Hello, PythonThe 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".