String methods

strip, split, join, replace and changing case.

Strings have methods, functions that are called with a dot: text.upper(). Strings are immutable, so every method returns a new string and the original stays the same:

name = "  Ada  "
clean = name.strip()
print(repr(name), repr(clean))   # '  Ada  ' 'Ada'

A common mistake is to call name.strip() and not save the result. The string does not change from that.

The methods you will use most:

  • lower(), upper(), title() change the case;
  • strip() removes spaces and line breaks at both ends, lstrip() and rstrip() only on one side;
  • replace(old, new) replaces every occurrence;
  • startswith(...) and endswith(...) check the beginning and the end;
  • find(sub) returns the index or -1, while index(sub) raises ValueError when the substring is missing;
  • count(sub) counts occurrences, isdigit() checks that the string consists of digits.

split cuts a string into a list. Without arguments it splits on any whitespace and drops the empty pieces. With an argument it splits exactly on the given separator:

print("a  b   c".split())      # ['a', 'b', 'c']
print("a,,b".split(","))       # ['a', '', 'b']

The reverse operation is join. It is called on the separator and takes a list of strings: ", ".join(["tea", "coffee"]) gives tea, coffee. Methods can be chained: text.strip().lower().replace(" ", "_"). It reads from left to right: each next method works on the result of the previous one.

Practice

  1. Split and join

    What does the program print?

    print("-".join("a b c".split()))
    
  2. What is true about methods

    Mark the true statements about string methods.

    • Methods return a new string
    • s.upper() changes s itself
    • split() with no arguments splits on any whitespace
    • strip() also removes spaces in the middle of the string
  3. A tag from text

    Write a function clean_tag(text): remove the spaces at both ends, convert the text to lowercase, and join the words inside with a single hyphen, even if there were several spaces between them.