Python Strings

  • use "" or ''
  • for multiple lines use triple quotes ''' '''
  • strings are iterable, i.e. can look up characters in the string by index
  • can use negative indexes
  • strings are immutable, must create a new string
  • concatenate strings with + and multiple with *
    • these will not automatically add spaces between strings
  • string.upper() and string.lower() change the case of all the characters in the string to be upper or lower
  • string.capitalize() will just capitalize the first letter
  • create new string using using .format()
    • it looks for curly brackets and inserts the parameter
    • example: 'William {}'.format('Faulkner') creates the string 'William Faulkner'
    • example:
      n1 = input('Enter a noun: ')
      v = input('Enter a verb: ')
      adj = input('Enter a adj: ')
      n2 = input('Enter a noun: ')
      r = '''The {} {} the {}{}'''.format(n1, v, adj, n2)
  • .split(delimiter) will split into multiple strings at the delimiter
    • the delimiter is not in either string
  • .join() lets you add new characters to a string
    • example:
      first_three = 'abc'
      result = '+'.join(first_three)
      result is a+b+c
    • can also use with lists. example:
      words = ['The', 'fox', 'jumped', 'over', 'the', 'fence', '.']
      one_string = ' '.join(words)
      one_string is 'The fox jumped over the fence .'
  • .strip() strips leading and following white space from a string
  • can use in and not in keywords
  • '\' escape character
    • \n newline
  • slicing: name[start_index:end_index]
    • start_index is included, end_index is not included
    • works with strings and lists
    • example:
      ivan = 'In place of death there was light.'
      gives us 'In place of death'ivan[17:33]gives us ' there was light'
    • example:
      list = ['a', 'b', 'c', 'd', 'e']
      now list is ['a', 'b', 'c']
    • if start_index is 0 you can leave it empty [:end_index]
    • if end_index is last index in the iterable you can leave it empty [start_index:]
    • leaving both empty [:] returns the original iterable
  • .replace(param1, param2) replaces every occurrence of one character with another
    • first param is the string to replace and the second param is the replacement string
    • example:
      equ = 'All animals are equal.'
      equ = equ.replace('a', '@')
      equ is now 'All @nim@ls @re equ@l.'
  • string.index('character') returns the first index the param string occurs at

Copyright © 2022