My kitty cat likes %s,
My kitty cat likes %s,
My kitty cat fell on his %s
And now thinks he's a %s.
>>> poem = '''
… My kitty cat likes %s,
… My kitty cat likes %s,
… My kitty cat fell on his %s
… And now thinks he's a %s.
… '''
>>> args = ('roast beef', 'ham', 'head', 'clam')
>>> print(poem % args)
My kitty cat likes roast beef,
My kitty cat likes ham,
My kitty cat fell on his head
And now thinks he's a clam.
5. Запишите следующее письмо по форме с помощью форматирования нового стиля. Сохраните строку под именем letter (это имя вы используете в следующем упражнении):
Dear {salutation} {name},
Thank you for your letter. We are sorry that our {product} {verbed} in your
{room}. Please note that it should never be used in a {room}, especially
near any {animals}.
Send us your receipt and {amount} for shipping and handling. We will send
you another {product} that, in our tests, is {percent}% less likely to
have {verbed}.
Thank you for your support.
Sincerely,
{spokesman}
{job_title}
>>> letter = '''
… Dear {salutation} {name},
…
… Thank you for your letter. We are sorry that our {product} {verb} in your
… {room}. Please note that it should never be used in a {room}, especially
… near any {animals}.
…
… Send us your receipt and {amount} for shipping and handling. We will send
… you another {product} that, in our tests, is {percent}% less likely to
… have {verbed}.
…
… Thank you for your support.
…
… Sincerely,
… {spokesman}
… {job_title}
… '''
6. Создайте словарь с именем response, имеющий значения для строковых ключей 'salutation', 'name', 'product', 'verbed' (прошедшее время от слова глагола verb), 'room', 'animals', 'amount', 'percent', 'spokesman' и 'job_title'. Выведите на экран значение переменной letter, в которую подставлены значения из словаря response:
>>> response = {
…·····'salutation': 'Colonel',
…·····'name': 'Hackenbush',
…·····'product': 'duck blind',
…·····'verbed': 'imploded',
…·····'room': 'conservatory',
…·····'animals': 'emus',
…·····'amount': '$1.38',
…·····'percent': '1',
…·····'spokesman': 'Edgar Schmeltz',
…·····'job_title': 'Licensed Podiatrist'
…·····}
…
>>> print(letter.format(**response))
Dear Colonel Hackenbush,
Thank you for your letter. We are sorry that our duck blind imploded in your
conservatory. Please note that it should never be used in a conservatory,
especially near any emus.
Send us your receipt and $1.38 for shipping and handling. We will send
you another duck blind that, in our tests, is 1 % less likely to have imploded.
Thank you for your support.
Sincerely,
Edgar Schmeltz
Licensed Podiatrist
7. При работе с текстом вам могут пригодиться регулярные выражения. Мы воспользуемся ими несколькими способами в следующем примере текста. Перед вами стихотворение Ode on the Mammoth Cheese, написанное Джеймсом Макинтайром (James McIntyre) в 1866 году во славу головки сыра весом 7000 фунтов, которая была сделана в Онтарио и отправлена в международное путешествие. Если не хотите вводить это стихотворение целиком, используйте свой любимый поисковик и скопируйте его текст в программу. Или скопируйте его из проекта «Гутенберг». Назовите следующую строку mammoth:
>>> mammoth = '''
We have seen thee, queen of cheese,
Lying quietly at your ease,
Gently fanned by evening breeze,
Thy fair form no flies dare seize.
All gaily dressed soon you'll go
To the great Provincial show,
To be admired by many a beau
In the city of Toronto.
Cows numerous as a swarm of bees,
Or as the leaves upon the trees,
It did require to make thee please,
And stand unrivalled, queen of cheese.
May you not receive a scar as
We have heard that Mr. Harris
Intends to send you off as far as
The great world's show at Paris.
Of the youth beware of these,
For some of them might rudely squeeze
And bite your cheek, then songs or glees
We could not sing, oh! queen of cheese.
We'rt thou suspended from balloon,
You'd cast a shade even at noon,
Folks would think it was the moon
About to fall and crush them soon.
… '''
8. Импортируйте модуль re, чтобы использовать функции регулярных выражений в Python. Используйте функцию re.findall(), чтобы вывести на экран все слова, которые начинаются с буквы «с».
Мы определим переменную pat для шаблона и затем будем искать такой шаблон в строке mammoth:
>>> import re
>>> re = r'\bc\w*'
>>> re.findall(pat, mammoth)
['cheese', 'city', 'cheese', 'cheek', 'could', 'cheese', 'cast', 'crush']
\b означает, что нужно начать с границы между словом и не словом. Используйте такую конструкцию, чтобы указать либо на начало, либо на конец слова. Литерал c — это первая буква всех слов, которые мы ищем. \w означает любой символ слова, которое включает в себя буквы, цифры и подчеркивания (_). * означает ноль или больше таких символов. Целиком это выражение находит слова, которые начинаются с «с», включая слово с. Если вы не использовали простую строку (у таких строк r стоит прямо перед открывающей кавычкой), Python интерпретирует \b как возврат на шаг и поиск по таинственной причине ничего не найдет:
>>> pat = '\bc\w*'
>>> re.findall(pat, mammoth)
[]
9. Найдите все четырехбуквенные слова, которые начинаются с буквы «c»:
>>> pat = r'\bc\w{3}\b'
>>> re.findall(pat, mammoth)
['city', 'cast']
Вам нужен последний символ \b, чтобы указать на конец слова. В противном случае вы получите первые четыре буквы всех слов, которые начинаются с «с» и имеют как минимум четыре буквы:
>>> pat = r'\bc\w{3}'
>>> re.findall(pat, mammoth)
['chee', 'city', 'chee', 'chee', 'coul', 'chee', 'cast', 'crus']