Strings¶

In [5]:
'this is a string'
Out[5]:
'this is a string'

🎨 len¶

In [6]:
len('word and word')
Out[6]:
13

You can use len to get the length of a string.

🖌 Building Strings¶

In [7]:
'fire' + 'place'
Out[7]:
'fireplace'
In [8]:
'yo' * 2
Out[8]:
'yoyo'
In [9]:
'nan ' * 16 + 'batman!'
Out[9]:
'nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan batman!'
batman!

🖌 +=¶

In [10]:
message = 'Hello'
message = message + ' world!'
message
Out[10]:
'Hello world!'
In [11]:
message = 'Hello'
message += ' world!'
message
Out[11]:
'Hello world!'

🖌 String Iteration¶

In [12]:
for letter in 'this is a string':
    print(letter)
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g

🎨 Character classes¶

In [13]:
'a'.isalpha(), '8'.isalpha()
Out[13]:
(True, False)
In [17]:
'!' < '0'
Out[17]:
True
In [14]:
'abcdefg'.isalpha(), 'abc1234'.isalpha(), 'abc!'.isalpha()
Out[14]:
(True, False, False)
In [18]:
'a'.isdigit(), '8'.isdigit()
Out[18]:
(False, True)
In [19]:
'12345'.isdigit(), '12345pi'.isdigit(), '123.456'.isdigit()
Out[19]:
(True, False, False)
In [20]:
'a'.isalnum(), '8'.isalnum()
Out[20]:
(True, True)
In [21]:
'12345'.isalnum(), '12345pi'.isalnum(), '123.456'.isalnum()
Out[21]:
(True, True, False)
In [23]:
'a'.isspace(), '8'.isspace(), ' '.isspace()
Out[23]:
(False, False, True)
In [24]:
'A'.islower(), 'A'.isupper()
Out[24]:
(False, True)
In [26]:
'a'.islower(), 'a'.isupper(), '9'.islower(), '9'.isupper()
Out[26]:
(True, False, False, False)
In [27]:
'a'.upper(), 'a'.lower()
Out[27]:
('A', 'a')
In [28]:
'A'.upper(), 'A'.lower()
Out[28]:
('A', 'a')
In [29]:
characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_+=[]{}"\'|:;,./?<> \t\n'
In [30]:
# isalpha
alphas = ''
for character in characters:
    if character.isalpha():
        alphas += character
print(alphas)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
In [31]:
# isdigit
digits = ''
for character in characters:
    if character.isdigit():
        digits += character
print(digits)
0123456789
In [32]:
# isalnum
alphanumeric = ''
for character in characters:
    if character.isalnum():
        alphanumeric += character
print(alphanumeric)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
In [33]:
# isspace
spaces = ''
for character in characters:
    if character.isspace():
        spaces += character
print(spaces)
 	

😶
In [34]:
# isspace
spaces = []
for character in characters:
    if character.isspace():
        spaces.append(character)
print(spaces)
[' ', '\t', '\n']
In [35]:
# other stuff
symbols = ''
for character in characters:
    if not character.isspace() and not character.isalnum():
        symbols += character
print(symbols)
`~!@#$%^&*()-_+=[]{}"'|:;,./?<>
In [36]:
# upper and lower
uppers = ''
lowers = ''
for character in characters:
    if character.isupper():
        uppers += character
    elif character.islower():
        lowers += character
print(uppers)
print(lowers)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

👩🏻‍🎨 No Spaces¶

Write a function that replaces all space characters with dashes.

In [38]:
def no_spaces(text: str):
    """Replace all space characters with dashes"""
    sentence = ''
    for character in text:
        if character.isspace():
            character = '-'
        sentence += character
    return sentence
        
    sentence = ''
    for character in text:
        if character.isspace():
            sentence += '-':
        else:
            sentence += character
        
In [ ]:
def no_spaces(text):
    result = ''
    for c in text:
        if c.isspace():
            c = '-'
        result += c
    return result
In [39]:
print(no_spaces('BYU is the place to be.'))
BYU-is-the-place-to-be.
In [40]:
message = """This is a long,
multiline string.
It has multiple lines.
That is what "multiline" means. :)"""

print(message)
print()
print(no_spaces(message))
This is a long,
multiline string.
It has multiple lines.
That is what "multiline" means. :)

This-is-a-long,-multiline-string.-It-has-multiple-lines.-That-is-what-"multiline"-means.-:)
In [41]:
print(no_spaces('Goodbye spaces \t tabs \n and newlines'))
Goodbye-spaces---tabs---and-newlines

👨🏾‍🎨 Numbers?¶

Write a function that replaces every number in a string with ?

In [46]:
def no_numbers(text):
    """Replace every number with ?"""
    sentence = ''
    for character in text:
        if character.isdigit():
            character = 'REDACTED'
        sentence += character
    return sentence
In [ ]:
def no_numbers(text):
    result = ''
    for char in text:
        if char.isdigit():
            result = result + '?'
        else:
            result = result + char
    return result
In [47]:
no_numbers('There were 7 people.')
Out[47]:
'There were REDACTED people.'
In [48]:
no_numbers('15 out of 25 have more than 17.3% contamination.')
Out[48]:
'REDACTEDREDACTED out of REDACTEDREDACTED have more than REDACTEDREDACTED.REDACTED% contamination.'
In [49]:
no_numbers('2 + 2 = 5, for large values of 2.')
Out[49]:
'REDACTED + REDACTED = REDACTED, for large values of REDACTED.'

🧑🏻‍🎨 Sum of Digits¶

Add up all the digits found in a string.

In [53]:
def find_digits(text):
    """Return a list of all the digits as ints"""
    digits = []
    for char in text:
        if char.isdigit():
            digits.append(int(char))
    return digits


def add_digits(text):
    """Add all the digits found in the `text`. 
    
    >>> add_digits('123foo')
    6
    """
    return sum(find_digits(text))
In [54]:
def add_digits(text):
    """Add all the digits found in the `text`. 
    
    >>> add_digits('123foo')
    6
    """
    total = 0
    for c in text:
        if c.isdigit():
            total += int(c)
    return total
In [55]:
add_digits('123foo')
Out[55]:
6
In [56]:
add_digits('10 students ate 6 oranges and 42 students ate 7 pears.')
Out[56]:
20

🧑🏽‍🎨 Organized¶

Write a program that "organizes" user input.

"Organized" text means that all the characters are reordered to this sequence:

  • lowercase letters
  • uppercase letters
  • digits
  • everything else
  • whitespace is removed

organize.py¶

Text: Hello, what is your name?
ellowhatisyournameH,?
Text: BYU is my favorite school!
ismyfavoriteschoolBYU!
Text: 3.14159 is a loose approx. for PI.
isalooseapproxforPI314159...
Text:

Key Ideas¶

  • String iteration
  • 'foo' + 'bar', 'BYU! ' * 5
  • .isalpha(), .isdigit(), .isalnum(), .isspace(), .isupper(), .islower()
  • .upper(), .lower()
  • +=