Python Forum
lists, strings, and byte strings
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
lists, strings, and byte strings
#2
Hm, let's try:

str.join('', list('Hello World'))
Output:
'Hello World'
Success :-)

Now the first try with bytes:
bytes.join(b'', list(b'Hello Bytes'))
Error:
TypeError: sequence item 0: expected a bytes-like object, str found
This is the problem with the representation. Iterating over bytes returns integers.

Third try:
bytearray(list(b'Hello Bytes'))
Output:
bytearray(b'Hello Bytes')
This looks better.

Finally you can use this:
bytes(bytearray(list(b'Hello Bytes')))
Output:
b'Hello Bytes'
But you're right. It's not so easy.

Bonus:
Instead of using the list function to construct a list,
use a bytearray. A bytearray is mutable and acts like a list.
bytes(bytearray(b'Hello Bytes'))
Output:
b'Hello Bytes'
It's mutable. You can mutate it.
ba = bytearray(b'Hello Bytes')
ba[0] = b'W'
Error:
TypeError: an integer is required
A not so nice solution for it:
ba[0] = ord(b'W')
ba
Output:
bytearray(b'Wello Bytes')
Extending:
ba.extend(b' This is the next Chunk')
ba
Output:
bytearray(b'Wello Bytes This is the next Chunk')
But i know what you mean. Handling with bytes a bit pain in the ass.
There must be a better way.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
lists, strings, and byte strings - by Skaperen - Mar-01-2018, 01:44 AM
RE: lists, strings, and byte strings - by DeaD_EyE - Mar-01-2018, 02:10 AM
RE: lists, strings, and byte strings - by Skaperen - Mar-02-2018, 02:12 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] Pad strings to always get three-digit number? Winfried 2 364 Jan-27-2024, 05:23 PM
Last Post: Winfried
  Tab Delimited Strings? johnywhy 7 590 Jan-13-2024, 10:34 PM
Last Post: sgrey
Question [PyMuPDF] Grab all strings of a given size? Winfried 3 685 Dec-26-2023, 07:39 AM
Last Post: Pedroski55
  How to read module/class from list of strings? popular_dog 1 483 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  Hard time trying to figure out the difference between two strings carecavoador 2 685 Aug-16-2023, 04:53 PM
Last Post: carecavoador
  Trying to understand strings and lists of strings Konstantin23 2 775 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  problem in using int() with a list of strings akbarza 4 715 Jul-19-2023, 06:46 PM
Last Post: deanhystad
  Taking Mathematical Expressions from Strings quest 2 718 Jul-02-2023, 01:38 PM
Last Post: Pedroski55
  xml indent SubElements (wrapping) with multiple strings ctrldan 2 1,491 Jun-09-2023, 08:42 PM
Last Post: ctrldan
  Delete strings from a list to create a new only number list Dvdscot 8 1,554 May-01-2023, 09:06 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020