What other string methods are there?


#1

Question

In the context of this lesson, which covered some important Python string methods, what other string methods are there?

Answer

There are many other useful string methods available in Python, which you can further check out in the documentation.

Here are a few other methods which you might find useful, with examples that will be using this string,

string = "abcabcabc"

The .count() method is one other useful method that returns the number of non-overlapping occurrences of some substring in a given range of indices.

print(string.count("abc")) # 3

The .encode() method encodes a string into a bytes object, which can be useful for things such as calculating a hash value of a string for use in a hash map data structure.

print(sum(string.encode())) # 882

The .startswith() and .endswith() methods are useful if you need to check whether a string is a prefix or a suffix of another string.

print(string.startswith("bab")) # False

print(string.endswith("abc")) # True