Теперь запакуем строку.
В этом случае следует передавать тип данных bytes.
>>> struct.pack('=s', b'a')
b'a'
Для записи слова следует указывать количество символов.
>>> struct.pack('=5s', b'hello')
b'hello'
Кстати, запакованный вид соответствует исходному тексту. Всё верно, символ есть в таблице ASCII, то есть его код попадает в диапазон 0-127, он может быть записан одним байтом и имеет визуальное представление. А вот что будет если добавить символ вне ASCII
>>> struct.pack(f'=s', b'ё')
SyntaxError: bytes can only contain ASCII literal characters.
Ошибка возникла еще на этапе создания объекта bytes, который не может содержать такой символ. Поэтому надо кодировать эти байты из строки.
>>> enc = 'ёжик'.encode('utf-8')
>>> struct.pack(f'={len(enc)}s', enc)
b'\xd1\x91\xd0\xb6\xd0\xb8\xd0\xba'
Заметьте, длина такой строки в байтах отличается от исходной длины, так как символы вне ASCII записываются двумя байтами и более. Поэтому здесь формат создаём на лету, используя получившуюся длину как каунтер токена.
#libs#basic
🌍 In 2023, explorers finished mapping over 75% of the world’s seafloor in high detail, uncovering thousands of undersea mountains and canyons hidden beneath the oceans. ✨
#exploration⚡#mapping⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Over 80% of Earth’s ocean remains unmapped and unexplored by humans. Modern sonar and robotic submersibles are revealing new mountains, trenches, and species with every deep-sea journey. ✨
#exploration⚡#ocean⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The first map to show the Americas as a separate continent was made by German cartographer Martin Waldseemüller in 1507. It’s where the name “America” first appeared on a world map. ✨
#cartography⚡#history⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In 2022, explorers used sonar to map a hidden undersea volcano off Madagascar’s coast, revealing a peak 800 meters tall that was completely unknown before their expedition. ✨
#exploration⚡#discovery⚡#oceans⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 While mapping the ocean floor in 1947, researchers aboard HMS Challenger discovered the Mid-Atlantic Ridge, revealing Earth's largest mountain range hidden underwater. This seismic finding triggered the theory of plate tectonics—explaining how continents drift. The ridge stretches for over 16,000 kilometers beneath the Atlantic Ocean. ✨
#discovery⚡#geology⚡#oceanography
👉subscribe Interesting Planet
👉more Channels