SyntaxStudy
Sign Up
Python String Methods — Part 2
Python Beginner 8 min read

String Methods — Part 2

String Methods — Part 2

More powerful string methods for searching, replacing, and testing string content.

replace() & find()

s = "I love cats and cats love me"
print(s.replace("cats", "dogs"))
# "I love dogs and dogs love me"
print(s.replace("cats", "dogs", 1))
# "I love dogs and cats love me"

print(s.find("cats"))    # 7
print(s.rfind("cats"))   # 16
print(s.find("fish"))    # -1 (not found)

count()

print(s.count("cats"))   # 2
print(s.count("love"))   # 2

startswith() & endswith()

url = "https://example.com"
print(url.startswith("https"))  # True
print(url.endswith(".com"))     # True
print(url.startswith(("http", "https")))  # True

Other Useful Methods

print("abc123".isalnum())   # True
print("   ".isspace())      # True
print("HELLO".isupper())    # True
print("hello".isalpha())    # True
Example
s = "Hello, Python!"
print(s.find("Python"))         # 7
print(s.count("l"))             # 3
print(s.replace("Hello", "Hi")) # Hi, Python!
print(s.startswith("Hello"))    # True
print(s.endswith("!"))          # True
Pro Tip

Use find() when you want to check existence without an exception. Use index() when you expect the substring to be there — it raises ValueError if missing.