Search strings

There are many functions in Python to search strings for specific information. Here are some of them:

  • count(value) – counts how many times the value in the parenthesis appear in a string.
  • endswith(value) – returns True if a string ends with the value specified in the parenthesis.
  • find(value) – searches the string for a value specified in the parenthesis and outputs the index of the location.
  • replace(old, new) – replaces all occurances of old with new.

Here are a couple of examples:

>>> newString='Hello world!'
>>> newString.count('world')
1
>>> newString.endswith('!')
True
>>> newString.find('llo')
2
>>> newString.replace('Hello', 'Bye')
'Bye world!'
Geek University 2022