Finding and replacing

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data scientist

Finding substrings

  • Search target string for a specified substring.

my_string = "Where's Waldo?"
my_string.find("Waldo")
8
my_string.find("Wenda")
-1
Regular Expressions in Python

Finding substrings

  • Search target string for a specified substring.

my_string = "Where's Waldo?"
my_string.find("Waldo", 0, 6)
-1
Regular Expressions in Python

Index function

  • Similar to .find(), search target string for a specified substring.

my_string = "Where's Waldo?"
my_string.index("Waldo")
8
my_string.index("Wenda")
File "<stdin>", line 1, in <module> 
ValueError: substring not found
Regular Expressions in Python

Index function

  • Similar to .find(), search target string for a specified substring.

my_string = "Where's Waldo?"
try:
    my_string.index("Wenda")
except ValueError:
      print("Not found")
"Not found"
Regular Expressions in Python

Counting occurrences

  • Return number of occurrences for a specified substring.

my_string = "How many fruits do you have in your fruit basket?"
my_string.count("fruit")
2
my_string.count("fruit", 0, 16)
1
Regular Expressions in Python

Replacing substrings

  • Replace occurrences of substring with new substring.

my_string = "The red house is between the blue house and the old house"
print(my_string.replace("house", "car"))
The red car is between the blue car and the old car
print(my_string.replace("house", "car", 2))
The red car is between the blue car and the old house
Regular Expressions in Python

Wrapping up

  • String manipulation:

    • Slice and concatenate
    • Adjust cases
    • Split and join
    • Remove characters from beginning and end
    • Finding substrings
    • Counting occurrences
    • Replacing substrings
Regular Expressions in Python

Let's practice!

Regular Expressions in Python

Preparing Video For Download...