String slicing

  • some_str[0:4] returns a new string from indexes 0 to 3 of some_str
    • some_str = 'mycats will return myca
  • some_str[1:3] returns a new string from indexes 1 to 2
  • some_str[:4] assumes 0:4
  • some_str[3:] means start at index 1 until the end of the string
  • negatives
    • -1 is the last charater of a string
    • -2 is the second to last character of a string

many string methods and commparisons

  • replace(old, new)
  • find(x)
  • count(x)
  • ==, >, <
  • BE CAREFUL with is
some = "ABC"
some = some.replace("A", "B")
print(some.count("B"))
statement = "my favorite class is CS149"
if "CS149" in statement:
    print("found it")

more methods

  • returns True or False
    • isdigit(), islower(), startswith(x), etc.
  • lower(), upper(), etc.
  • textbook has many examples

Splitting and joining strings

mary = 'Mary had a little lamb'
words_mary = mary.split()  # words_mary is a list of strings. default space separtes tokens
print(f'the entire list: {words_mary}  the first string in the list:  {words_mary[0]}' )
new_mary = "**".join(words_mary)
print(new_mary)
  • can also use + to join strings
mystring = ""
for i in range(44):
    if (i % 5 == 1):
        mystring += str(i)
        mystring += "---"
print(mystring)

List slicing

  • use [:] as with strings
  • when used on a list, returns a list
cs_class = ['CS149', 'CS159', 'CS227', 'CS240', 'CS261']
print(f'Freshman classes {cs_class[0:3]}')

odd_list = [1, 'sally', 4.5, 0, 'ball']
print(f' print something {odd_list[-5:-2]}')

List methods

  • many, see textbook
  • recall a list is mutable so can change the list
    • recall a string is immutable
  • sort() : sorts the list
  • sorted() : sorts the list but does not modify list, instead creates and returns a new list
  • reverse=True option to sort in reversed order

Interesting example in the textbook

numbers = [int(i) for i in input('Enter numbers: ').split()]
sorted_numbers = sorted(numbers)
print(f'\nOriginal numbers: {numbers}')
print(f'Sorted numbers: {sorted_numbers}')