Section #3 Solutions


Written by Elyse Cornwall


String Slicing

Part 1

                    
s = 'PythonTime'
    [0123456789]
                    
                    
  • 'ython' [1:6]
  • 'onTime' [4:10] or [4:]
  • 'T' s[6]
  • 'PYTHONTIME' s.upper()
  • 'tim' s[6:9].lower()

Part 2

                        
>>> s = 'a#xyz&TTT'
        [012345678]

>>> hash = s.find('#')
>>> amper = s.find('&')
>>> s[hash + 1: amper] # The substring between the '#' and '&' chars
>>>
>>> s[hash: amper + 1] # The substring starting at the '#' char and ending at the '&' char.
>>> 
>>> s[amper + 1:].lower() # The substring starting after the '&' char to the end of the string converted to lowercase.
                        
                    


Bleeping File Reading

                    
import random
import sys

SAFE_WORDS = ['BLEEP', 'REDACTED', 'XXXXXXX']


def bleep_line(line, replacement):
    '''
    First, implement the function bleep_line(line, replacement),
    which takes in a string line and a string replacement and
    returns the line with any bad words replaced with whatever
    the replacement string is. We identify bad words using square
    brackets - [[bad word]] - and the string line will contain
    one or zero instances of bad words.
    >>> bleep_line('What the [[heck]] Richard??', 'BLEEP')
    'What the BLEEP Richard??'
    >>> bleep_line('They call him [[Lord Voldemort]]', 'He Who Must Not Be Named')
    'They call him He Who Must Not Be Named'
    >>> bleep_line('I do not need to swear to express my emotions', 'BLEEP')
    'I do not need to swear to express my emotions'
    '''
    start = line.find("[[")
    end = line.find(']]')
    if start == -1:
        return line
    if end == -1:
        return line
    left = line[:start]
    right = line[end + 2:]
    return left + replacement + right


def file_bleeping(filename):
    '''
    Now, we're going to write a function called file_bleeping(filename)
    that takes in the name of a text file filename, and prints the
    contents of the file with each line bleeped out. Just like in the
    previous part of this assignment, you can assume that each line only
    contains a single item to be bleeped out, or none at all.

    Hint, hint: use your helper function from the previous part to
    implement this function!
    '''
    with open(filename) as f:
        for line in f:
            line = line.strip()
            replacement = random.choice(SAFE_WORDS)
            bleeped_line = bleep_line(line, replacement)
            print(bleeped_line)


if __name__ == "__main__":
    args = sys.argv[1:]
    file_bleeping(args[0])
                    
                    

Slice Num

                            
import sys


def slice_num(s):
    """
    In this problem, you'll write a function slice_num(s)
    that takes in a string s and returns the integer contained
    in that string. If the string contains an integer, it will
    be between two hashtags. If there are no hashtags, you can
    return 0. There will be at most one integer per line.

    Write some Doctests!
    """
    start = s.find('#')
    if start == -1:                     # no hashtags
        return 0
    end = s.find('#', start + 1)     # look for second hashtag after first hashtag index
    num = s[start + 1:end]
    return int(num)


def sum_nums(s1, s2):
    """
    Implement the function sum_nums(s1, s2) that takes in two strings
    and returns the sum of the integers in those strings. As in
    slice_num(s), any integers in these strings will be between two
    hashtags, and each string will have at most one integer, or none.
    Calculate the sum, then return it. Hint: this would be a great place
    to use the helper function you just wrote!

    >>> sum_nums('#1#', 'plus #2# equals')
    3
    >>> sum_nums('abc#123#xyz', 'no nums here!')
    123
    >>> sum_nums('', '')
    0
    """
    sum = slice_num(s1) + slice_num(s2)
    return sum


if __name__ == "__main__":
    sum_nums('My favorite number is #2#', 'Well, I prefer #5# instead.')
    print('Should have printed: 7')