Python · strings

String Basics

Create text, pick out characters by position, slice, join and repeat.

Creating strings


        # string creation
        text = "Hello"
        text2 = 'World'
        multiline = """This is
        a multiline
        string"""
      

Single and double quotes mean the same thing; triple quotes let a string span several lines.

String indexing


          # access characters
          text = "Hello"
          text[0]
          # ans: 'H'
          text[-1]
          # ans: 'o'
          text[1]
          # ans: 'e'
        

Positions count from 0 on the left, or from -1 on the right.

String slicing


          text = "Hello, World!"
          text[0:5]
          # ans: 'Hello'
          text[7:]
          # ans: 'World!'
          text[:5]
          # ans: 'Hello'
        

[start:stop] includes start and stops before stop. A missing end means "to the edge".

String concatenation


        # combine strings
        "Hello" + " " + "World"
        # ans: "Hello World"
        greeting = "Hello"
        name = "Alice"
        greeting + ", " + name
        # ans: "Hello, Alice"
      

String repetition


        # repeat strings
        "Ha" * 3
        # ans: "HaHaHa"
        "=" * 10
        # ans: "=========="
      

String length


          # get the length
          len("Hello")
          # ans: 5
          len("")
          # ans: 0
        

Exercises

Predict each result, then press → to see which characters are picked.

Exercise 1


          # negative index?
          s = "Python"
          s[-1]
          # ans: 'n'
          s[-2]
          # ans: 'o'
        

Exercise 2


          # slicing with a step?
          s = "abcdefg"
          s[::2]
          # ans: 'aceg'
        

The third number is the step: take every 2nd character.

Exercise 3


          # reverse a string?
          s = "Hello"
          s[::-1]
          # ans: 'olleH'
        

A step of -1 walks from the right end to the left: the small numbers show the order.

Exercise 4


          # string immutability?
          s = "Hello"
          s[0] = 'h'
          # ans: TypeError (strings are immutable)
        

Make a new string instead: s = 'h' + s[1:].

Exercise 5


        # concatenation vs join?
        "a" + "b" + "c"
        # ans: "abc"
        "".join(["a", "b", "c"])
        # ans: "abc"
      

Exercise 6


          # membership test?
          "ell" in "Hello"
          # ans: True
          "xyz" in "Hello"
          # ans: False
        

Exercise 7


        # empty string?
        s = ""
        len(s)
        # ans: 0
        bool(s)
        # ans: False
      

Exercise 8


        # string multiplication?
        "0" * 5
        # ans: "00000"
      

Exercise 9


          # escape characters?
          s = "Line1\nLine2"
          len(s)
          # ans: 11 (\n is one character)
        

Exercise 10


          # raw string?
          s = r"C:\new\path"
          # ans: "C:\\new\\path"
        

In a raw string a backslash is just a backslash, so \n stays two characters. Python shows each one doubled when it prints the value.

Remember

Index from 0

s[0] is the first character, s[-1] the last.

Slices stop early

s[a:b] runs from a up to, not including, b; s[::-1] reverses.

Immutable

You can't change a character in place; build a new string.

+, *, in, len

Join, repeat, search and measure.