encode string Python

Содержание
Введение
Синтаксис
Примеры
Похожие статьи

Введение

Метод encode() возвращает закодированную версию строки.

Кодировка по умолчанию - это текущая строковая кодировка по умолчанию. Ошибки могут быть указаны для установки другой схемы обработки ошибок.

Синтаксис

str.encode(encoding = 'UTF-8',errors = 'strict')

Пример работы encode()

>>> s = "abcd" >>> len(s) 4 >>> s.encode() b'abcd' >>> s = "сайт" >>> len(s) 4 >>> s.encode() b'\xd1\x81\xd0\xb0\xd0\xb9\xd1\x82' >>> s = "сайт" >>> s.encode('iso-8859-5') b'\xe1\xd0\xd9\xe2' >>> s.encode('utf-8') b'\xd1\x81\xd0\xb0\xd0\xb9\xd1\x82'

Японские символы

>>> j = "平仮" >>> len(j) 2 >>> j.encode() b'\xe5\xb9\xb3\xe4\xbb\xae' >>> j.encode("SHIFT-JIS") b'\x95\xbd\x89\xbc'

Преобразовать в "кириллический" iso-8859-5 не получится

>>> j.encode('iso-8859-5') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.8/encodings/iso8859_5.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1: character maps to <undefined>

j.encode('iso-8859-5') # это тоже что и j.encode('iso-8859-5', errors='strict')

>>> j.encode('iso-8859-5', errors='ignore') b'' >>> j = "Japanese symbol 平仮" >>> j.encode('iso-8859-5', errors='ignore') b'Japanese symbol '

Article author: Andrei Olegovich

Похожие статьи
Built-in Collections
Строки
Python
f-string
format string
encode()
Перенос слишком длинной строки на новую

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: