group = 'Python Toronto'
f'Hello {group}!'
{ }
¶f'Hello {group.upper()}!'
dict
¶portfolio = {'AAPL': 222.77, 'RHT': 122.31, 'GOOGL': 1111.77}
f'${portfolio['GOOGL']}USD'
f"${portfolio['GOOGL']}USD"
f"${portfolio['GOOGL']:,}USD"
class
...¶class Drink:
def __init__(self, name, caffine):
self.name = name
self.caffine = caffine
def __str__(self):
return f'{self.name}'
def caffine_for_quantity(self, size=100000):
return (
f'{self.name} has {self.caffine*size:.0f} '
f'mg for {size/1000:.0f} grams.'
)
coffee = Drink('Coffee', .0004)
f'{coffee.caffine_for_quantity()}'
f'{coffee.caffine_for_quantity(459732)}'
import timeit
format_funcs = {
'f-strings': """
def format(superhero, rank):
return f'{superhero} has a rank of {rank}!'
""",
'%-formatting': """
def format(superhero, rank):
return '%s has a rank of %s!' % (superhero, str(rank))
""",
'.format()': """
def format(superhero, rank):
return '{} has a rank of {}!'.format(superhero, str(rank))
""",
'concatenation +': """
def format(superhero, rank):
return superhero + ' has a rank of ' + str(rank) + '!'
""",
'concatenation ()': """
def format(superhero, rank):
return superhero, ' has a rank of ', str(rank), '!'
"""
}
test_func = """def test_format():
for superhero in ('Wonder Woman', 'Supergirl', 'Batman', 'Robin'):
for rank in range (1, 101):
format(superhero, rank)
"""
for key, func in format_funcs.items():
print(key, timeit.timeit('test_format()', func + test_func, number=10000))
%matplotlib inline
import pandas as pd
df = pd.DataFrame([
{'method': 'f-strings', 'time': 1.2444629460001124},
{'method': '%-formatting', 'time': 2.323644578999847},
{'method': '.format()', 'time': 3.0558486750001066},
{'method': 'concatenation +', 'time': 2.0393622280003},
{'method': 'concatenation ()', 'time': 1.4142364679996717}
])
df.sort_values('time').plot(kind='barh', x='method', y='time')