Strings

A string is a sequence of characters (an ordered collection of characters), and is delimited by paired single or double quotes, e.g. "This is a string." It is a new type (str) for us. In this section, you will learn about the string data structure and how to work with it. In particular you will learn indexing and iteration.

Readings from the book The Practice of Computing Using Python.

Chapter 4: Strings

Videos

  1. Strings
  2. A string is a sequence of characters and is delimited by quotes.

    1. Introduction
    2. String Indexing
    3. a_string[i], indexing starts at 0, negative indexing starts from end.
      a_string[x:y], a slice from index x up to but not including index y.
      a_string[x:y:z], a slice from index x up to but not including index y with step z.
      Defaults: no x, start slice at beginning; no y, end slice at end.
      Idiom: a_string[::-1] is the reverse of a_string.

    4. String Methods
    5. List of string methods

    6. String Comparison
    7. String Formatting using the .format() method
    8. String Formatting: Tutorial .format()

      String Formatting: Tutorial f-strings

      year = 2024
      stats = 'population'
      number = 345426571.56
      percent = 4.2346
      using_format = "the US{:5d}{:>11s} is estimated at {:,.1f} people\nwhich is equivalent to {:.2f}% of the world population".format(year, stats, number, percent)
      using_fstring = f"the US{year:5d}{stats:>11s} is estimated at {number:,.1f} people\nwhich is equivalent to {percent:.2f}% of the world population"            
      print(using_format)
      print(using_fstring)
      
      the two print statements will result in the same string:
      the US 2024 population is estimated at 345,426,571.6 people
      which is equivalent to 4.23% of the world population
      
  3. Iteration: repitition using for
  4.              for item in collection:
                    suite-of-statements 
    1. Iteration: for
  5. Examples using strings and for.
    1. Let's shout!
    2. We use uppercase characters to SHOUT when typing text. Let's write a program that converts every lowercase character to an uppercase character.

    3. Palindromes.
    4. A palindrome is a string that is the same forwards and backwards. Case is ignored as are non-alphabetic and non-numeric characters. For example, "Madam, I'm Adam" is a palindrome.

Assignments

  1. Chapter 4 Exercises on Codio
  2. Lab03 (do pre-lab first on D2L)
  3. Project03