Простой Python. Современный стиль программирования (Любанович) - страница 277

>>>> import unicodedata

>>>> mystery = '\U0001f4a9'

>>>> mystery

>' '

>>>> unicodedata.name(mystery)

>'PILE OF POO'

Ой-ой-ой! Что еще у них там есть?

2. Закодируйте строку mystery, в этот раз с использованием кодировки UTF-8, в переменную типа bytes с именем pop_bytes. Выведите на экран значение переменной pop_bytes:

>>>> pop_bytes = mystery.encode('utf-8')

>>>> pop_bytes

>b'\xf0\x9f\x92\xa9'

3. Используя кодировку UTF-8, декодируйте переменную pop_bytes в строку pop_string. Выведите на экран значение переменной pop_string. Равно ли оно значению переменной mystery?

>>>> pop_string = pop_bytes.decode('utf-8')

>>>> pop_string

>' '

>>>> pop_string == mystery

>True

4. Запишите следующее стихотворение с помощью старого стиля форматирования. Подставьте строки 'roast beef', 'ham', 'head' и 'clam' в эту строку:

>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: