More Strings¶

🎨 .split()¶

In [ ]:
question = 'Do you know the muffin man?'
print(question.split())
In [ ]:
statement = "It is possible that I might, under other circumstances, have something to say, but right now I don't"
print(statement.split(','))

NOTES

  • you can split on more than just white space
  • in this example, ',' is the delimiter

The string you use as the separator is called the delimiter

In [ ]:
text = "This  string   has\nvery     unusual    \n     whitespace!"
print(text)
In [ ]:
text.split()
In [ ]:
text.split(' ')
In [ ]:
text.split('\n')

NOTES

  • When no argument is provided, split will combine all whitespace into a single delimiter

🎨 .join()¶

In [ ]:
' '.join(['a','bunch','of','words'])
In [ ]:
','.join(['45', '670', '324'])
In [ ]:
sentences = [
    'This is the first line.', 
    'This is the second line.', 
    'And here is another line for good measure.'
]
print(sentences)
In [ ]:
text = '\n'.join(sentences)
print(text)
In [ ]:
' and '.join(['apples','oranges','bananas','pears'])

NOTES

  • you can join on more than a single character
  • notice also that the delimiter goes in between, but not before or after the items in the list
In [ ]:
'  '.join('Cougars')

NOTES

  • you can join anything that is iterable and returns a sequence of strings
In [ ]:
' '.join([1, 2, 3, 4])

NOTES

  • you can only join strings
  • first convert to strings, then join

🖌 random¶

NOTES

  • For each example, demonstrate how running the code again yields different results

random.choice()¶

In [ ]:
import random

fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)
print(selection)

random.randint()¶

In [ ]:
import random

print(random.randint(1, 10))

NOTES

  • Note that random.randint() can return the boundary numbers
    • so, the return number is anything including and between the arguments.

random.random()¶

In [ ]:
print(random.random())

If you need a random float between 0 and 100, just scale the random number:

In [ ]:
print(random.random() * 100)

random.sample()¶

In [ ]:
name = 'Washington'
In [ ]:
print(random.sample(name, 2))
In [ ]:
print(random.sample(name, 5))
In [ ]:
print(random.sample(name, len(name)))

random.sample can be used to get a random sample from a collection.

If you sample all the items in the collection, you essentially get a shuffled version of the data.

🖌 Events at Random Frequency¶

In [ ]:
%%file apples.py
def apples(size):
    result = []
    while len(result) < size:
        if random.random() < 0.1:
            result.append('bananas!')
        else:
            result.append('apples')
    return result

size = int(sys.argv[1])
fruit = apples(size)
print(' '.join(fruit))

apples.py¶

🧑🏼‍🎨 Umm...¶

Randomly inject "umm" into a given sentence at a frequency of about 20%.

umm.py¶

NOTES

  • Draw it out!
    • Sentence -> words -> words with umm -> sentence
In [ ]:
import random
import sys


def ummify(words):
    """Randomly inject 'umm' into the given text at a frequence of 20%"""
    words = text.split(' ')
    result = []
    for word in words:
        if random.random() < 0.2:
            result.append('umm')
        result.append(word)
    return ' '.join(result)


text = sys.argv[1]
print(ummify(text))
python umm.py "So, I've been meaning to ask, will you go out on a date with me?"

🖌 Early Return¶

In [ ]:
def has_digit(text):
    """Returns true if any character in `text` is a digit"""
    for char in text:
        if char.isdigit():
            return True
    return False

NOTES

  • The for loop never gets to finish. That's OK.
  • return False is correct because if we didn't return True, we never found a digit.
  • This pattern comes up often when you are checking for the existing or absence of some property
In [ ]:
has_digit('abcdefg123')
In [ ]:
has_digit('a few words')

👩🏻‍🎨 has_byu¶

In [ ]:
def has_byu(lines):
    """Returns True if any of the lines contain the text 'BYU'
    lines = ['abc', 'byu', '123'] => True
    lines = ['123', 'abc'] => False
    """
    for line in lines:
        if 'BYU' in line or 'byu' in line:
            return True
    return False
    
In [ ]:
def has_byu(lines):
    """Returns True if any of the lines contain the text 'BYU'"""
    for line in lines:
        if 'BYU' in line:
            return True
    return False
In [ ]:
has_byu(['Yesterday I hiked Y mountain','I saw a squirrel','The squirrel ran away'])
In [ ]:
has_byu(['I need to buy books','The BYU bookstore has chocolate-covered cinnammon bears','I have a plan!'])

👨🏼‍🎨 all_digits¶

In [ ]:
def all_digits(text):
    """Returns True if all of the characters are digits"""
    for char in text:
        if not char.isdigit():
            return False
    return True
In [ ]:
def all_digits(text):
    """Returns True if all of the characters are digits"""
    for c in text:
        if not c.isdigit():
            return False
    return True
In [ ]:
all_digits('12345')
In [ ]:
all_digits('123e32')

Key Ideas¶

  • .split() and .join()
  • random
  • Events at random frequency
  • Early return