Unit 2: Iteration

Strings

  • sequence of characters

  • can access each character by element

    • error if you try to access an element that does not exist

  • Elements start at 0

    • can access going negative (-1 is the last element, -n is the first element)

  • type of object

How to define and access a string

  • varName = “hello”

  • varName[0] —> h

  • type varName —> str (string)

Slicing: taking section of string

  • varName[0:3] —> hel

Length: len(varName)

  • gives you the number of elements in the string

Unicode

  • how to find unicode value: var = ord(‘yourCharacter)

  • how to find character from unicode value: var = chr(unicodeValue)

Methods that work w/ Strings

  • Count, replace, lower, upper, split

  • How to use: variableName.methodName(parameters)

    • myString = ‘I like to program with Python’

    • myString.count(‘i’)

      • there are 2 i’s in the string (both capital and lowercase)

    • myString.replace(“I”, “We”

      • myString = We like to program with Python

      • replaces capitalized I with We

    • myString.lower()

      • myString = i like to program with python

      • lowercase every letter

    • myString.upper()

      • myString = I LIKE TO PROGRAM WITH PYTHON

      • uppercase every letter

  • When you do methods, you NEED to save the change into a new variable, variable values will remain the same if you do not save it

Splitting (words of a string into a list)

  • myList = myString.split()

    • [‘I’, ‘like’, ‘to’, ‘prgram’, ‘with’, ‘Python’]

    How to access each word

    • myList[3] = ‘prgram’

    • the element is now the number associated with the word in the list not the letter

Objects

  • a string is an object

  • have certain functions that work just for them and their data

    • functions are called Methods

List