Skip to Content

Python 3 String Operations

  • lower(): Converts a string to the lowercase letter.
  • upper(): Converts a string to the uppercase letter.
  • islower() / isupper(): Checks if the whole string is in lower case or upper case and returns bool value respectively.
  • startswith(): Returns a bool value. Check if the given string starts with a particular text.
  • endswith(): Returns a bool value. Check if the given string ends with a particular text.
  • join(): Join different strings to make a single concatenated string. A list of strings is joined together into a single string.
  • split(): Reverse of join(). It splits a large string into smaller strings. By default, a string is split wherever characters such as space, tab or newline characters are found. However, a delimiter can be passed inside the split(). The string then will split when this delimiter is encountered.
  • ljust()/ rjust()/ center(): These three methods are for justifying text. The first argument is an integer length for the justified string, and the second argument is the fill character. ljust() fills the fill char on the left side, rjust() fills the fill char on the right side, and center() justifies the text at the center, filling the fill char at both left and right sides.
  • strip()/ lstrip()/ strip(): Removes whitespaces(space, tab and newline) from left side(lstrip()), right side(rstrip()) and from both sides(strip()).
  • index(): index() method finds the first occurrence of a particular character or text in the given string. In this example, the index position for the first occurrence of ‘r’ is printed.
  • count(): counts the total number of occurrences of a character in the given string. Character ‘o’ occurs thrice in the string “object-oriented programming.”
  • find(): find() method is similar to index() method. It also returns the index for the first occurrence. But the major difference is that if a character whose index is to find is not present, index() will throw an error while find() returns -1 (as shown in the output)
  • replace(): It replaces a text with another text in the given string. In this example, ‘e’ is being replaced by ‘3’.