Python · strings

String Methods

Change case, trim, split, join, search, replace and count, all with methods that return new strings.

Case methods


        # upper and lower
        "hello".upper()
        # ans: "HELLO"
        "HELLO".lower()
        # ans: "hello"
        "hello world".title()
        # ans: "Hello World"
        "hello".capitalize()
        # ans: "Hello"
      

Strip methods


          # remove whitespace
          "  hello  ".strip()
          # ans: "hello"
          "  hello  ".lstrip()
          # ans: "hello  "
          "  hello  ".rstrip()
          # ans: "  hello"
        

l = left end only, r = right end only.

Split


        # split a string into a list
        "apple,banana,cherry".split(",")
        # ans: ['apple', 'banana', 'cherry']
        "one two three".split()
        # ans: ['one', 'two', 'three']
      

With no argument, split() splits on any run of whitespace.

Join


        # join a list into a string
        ",".join(["a", "b", "c"])
        # ans: "a,b,c"
        " ".join(["Hello", "World"])
        # ans: "Hello World"
      

The string you call join on is the glue between the items.

Find and index


          # find a substring
          "hello world".find("world")
          # ans: 6
          "hello world".find("xyz")
          # ans: -1
          "hello world".index("world")
          # ans: 6
        

Both return the index where the match starts.

Replace


          # replace a substring
          "hello world".replace("world", "Python")
          # ans: "hello Python"
          "aaa".replace("a", "b", 2)
          # ans: "bba" (replaces the first 2)
        

startswith / endswith


          # check the start and end
          "hello".startswith("he")
          # ans: True
          "hello".endswith("lo")
          # ans: True
        

Count


          # count occurrences
          "hello".count("l")
          # ans: 2
          "banana".count("a")
          # ans: 3
        

Exercises

Predict each result, then press → to check.

Exercise 1


        # case methods?
        "HeLLo".lower()
        # ans: "hello"
        "hello".upper()
        # ans: "HELLO"
      

Exercise 2


          # strip only the ends?
          "  hello  ".strip()
          # ans: "hello"
        

Exercise 3


          # split with a limit?
          "a-b-c-d".split("-", 2)
          # ans: ['a', 'b', 'c-d']
        

Only the first 2 separators are used; the rest stays in the last piece.

Exercise 4


        # join with numbers?
        "-".join([1, 2, 3])
        # ans: TypeError (join needs strings)
        "-".join(["1", "2", "3"])
        # ans: "1-2-3"
      

Exercise 5


        # find vs index?
        "hello".find("x")
        # ans: -1
        "hello".index("x")
        # ans: ValueError
      

Exercise 6


        # replace all?
        "aaa".replace("a", "b")
        # ans: "bbb"
      

Exercise 7


          # case sensitive?
          "Hello".startswith("h")
          # ans: False
          "Hello".startswith("H")
          # ans: True
        

Exercise 8


          # count overlapping?
          "aaa".count("aa")
          # ans: 1 (non-overlapping)
        

After matching aa at 0, the search continues from index 2, where only one a is left.

Exercise 9


        # empty split?
        "".split()
        # ans: []
        "  ".split()
        # ans: []
      

Exercise 10


        # join an empty list?
        ",".join([])
        # ans: ""
      

Remember

New strings

Methods never change the original string; keep the result.

Case matters

find, count, startswith and friends compare exactly.

find vs index

-1 or a ValueError when the text isn't there.

split ↔ join

join only accepts strings.