Today: more string algorithms, str in, if/elif, quick-return, str find, slices

Note: running tests, green run button near bottom

See Python guide: string, if

Problems today:

> str2 functions

String in Test

>>> 'c' in 'abcd'
True
>>> 'bc' in 'abcd'
True
>>> 'bx' in 'abcd'
False
>>> 'A' in 'abcd'
False

1. Catty function

`'xCtxxxAax' → 'CtAa'`

Return a string made of the chars from the original string, whenever the chars are 'c' 'a' or 't', (either lower or upper case). So the string 'xCaxxxTx' returns 'CaT'.

Solution

def catty(s):
    result = ''
    for i in range(len(s)):
        # Create "low" var of intermediate result
        low = s[i].lower()
        if low == 'c' or low == 'a' or low == 't':
            result += s[i]  # Use original, not low
    return result
    # Cute non-obvious alternative: use "in"
    # to do the "or" logic for us, like this:
    # if low in 'cat':

if/elif Structure

if test1:
  action-1
elif test2:
  action-2
else:
  action-3

2. str_adx()

Solution

def str_adx(s):
    result = ''
    for i in range(len(s)):
        if s[i].isalpha():
            result += 'a'
        elif s[i].isdigit():
            result += 'd'
        else:
            result += 'x'
    return result

Quick Return Strategy

3. first_alpha()

Given a string s, return the first alphabetic char in s, or None if there is no alphabetic char. Demonstrates quick-return strategy.

Solution

def first_alpha(s):
    for i in range(len(s)):
        if s[i].isalpha():
            return s[i]
            # 1. Exit immediately if found
    # 2. If we get here,
    # there was no alpha char.
    return None

4. has_digit()

Use quick-return strategy, returning True or False.

Given a string s, return True if there is a digit in the string somewhere, False otherwise.

    for i in range(len(s)):
        if s[i].isdigit():
            # 1. Exit immediately if found
            return True
    # 2. If we get here,
    # there was no digit.
    return False

String find()

>>> s = 'there'
>>> s.find('h')
1
>>> s.find('e')
2
>>> s.find('ere')   # len > 1 ok
2
>>> s.find('x')
-1
>>> s.find('E')
-1
>>> s.find('e', 3)  # start at 3
4

Python String Slices

alt:string 'Python' shown with index numbers 0..5

>>> s = 'Python'
>>> s[1:3]
'yt'
>>> s[1:5]
'ytho'
>>> s[3:3]    # "not including" dominates
''
>>>
>>> s[:3]     # omit = from/to end
'Pyt'
>>> s[4:]
'on'
>>> s[4:999]  # too big = to end
'on'
>>> s[:4]     # "perfect split" on 4
'Pyth'
>>> s[4:]
'on'
>>> s[:]      # the whole thing
'Python'

Brackets Problem

> brackets

Brackets Observations

Optional: Negative Slice

>>> s = 'Python'
>>> s[len(s)-1]
'n'
>>> s[-1]
'n'
>>> s[-2]
'o'
>>> s[1:-3]
'yt'
>>> s[-3:]
'hon'