Count the number of letters.
len('Bring me my Bow of burning gold;')
Strip peripheral whitespace.
' Bring me my Arrows of desire: '.strip()
Replace characters.
'Bring me my Spear: O clouds unfold!'.replace('Spear', 'Shrubbery')
Format template.
'Bring me my %s of fire!' % 'Chariot'
Test characters.
'I will not cease from Mental Fight,'.startswith('I')
Count occurrences.
'Nor shall my Sword sleep in my hand:'.count('my')
' ;) '.join([
'Welcome to all the pleasures that delight',
'Of ev\'ry sense the grateful appetite,',
])
Split a string into a list.
'Then lift up your voices, those organs of nature'.split(', ')
Make a list from another list.
words = "Those charms to the troubled and amorous creature.".split()
['*%s*' % x for x in words]
Get the length of each word.
# Type your solution here and press CTRL-ENTER
Make a dictionary of US state names.
code_by_state = {'California': 'CA', 'New York': 'NY', 'Virginia': 'VA'}
code_by_state
code_by_state.keys()
code_by_state['Florida'] = 'FL'
code_by_state
code_by_state['New York']
Make a dictionary of US state codes using a dictionary comprehension.
state_by_code = {code: state for state, code in code_by_state.items()}
state_by_code
# Get the state name for VA
state_by_code['VA']
Make a dictionary where each letter corresponds to a list of US states that start with that letter.
import csv
state_by_code = {code: state for state, code in csv.reader(open('datasets/USA-StateAbbreviations.csv'))}
state_by_code['MA']
import collections
codes_by_letter = collections.defaultdict(list)
for code in state_by_code:
letter = code[0].lower()
codes_by_letter[letter].append(code)
print(codes_by_letter['a'])
print(codes_by_letter['m'])
def add(x, y):
return x + y
add(1, 2)
multiply = lambda x, y: x * y
multiply(1, 2)
Make a list of functions.
methods = [add, multiply]
methods
import random
for x in range(5):
combine = random.choice(methods)
print(combine(4, 5))
Define a function that returns a list of links on a webpage.
import requests
from bs4 import BeautifulSoup
def get_links(url):
html = requests.get(url).content
links = BeautifulSoup(html, 'lxml').find_all('a')
return [link.get('href') for link in links]
Look at the first five links on a webpage.
get_links('http://google.com')[:5]
Count the number of links on a webpage.
# Type your solution here and press CTRL-ENTER
Classes can contain variables and methods.
class Animal(object):
def __init__(self, name):
self.name = name
self.stomach = []
def __repr__(self):
return self.name
def ask(self):
return '%s is %s.' % (self.name, 'full' if self.stomach else 'hungry')
def eat(self, food):
if food in self.stomach:
print('%s already ate %s.' % (self.name, food))
else:
print('%s eats %s!' % (self.name, food))
self.stomach.append(food)
turtle = Animal('Donatello')
dinosaur = Animal('Barney')
monster = Animal('Cookie Monster')
monster.ask()
monster.eat(turtle)
monster.eat(turtle)
monster.stomach
turtle in monster.stomach
dinosaur in monster.stomach
words = 'why do bees make honey'.split()
for index, word in enumerate(words):
print(index, word)
boys = 'Roy', 'Oak', 'Cedar', 'Rock'
girls = 'Cathaleen', 'Sienna', 'Holly', 'Sapphire'
list(zip(boys, girls))
def walk_numbers():
print('searching...')
for i in range(10):
yield i
print('not found!')
# Stop as soon as the condition is met using any()
print('has_condition = %s' % any(x > 5 for x in walk_numbers()))
print()
print('has_condition = %s' % any(x > 10 for x in walk_numbers()))
We recommend the Official Python Tutorial.