Python list of strings to bytes

I would write a list on serial COM through pySerial.

I create a list of string, where each string is a parameter, and then I pass the list to serial write function. There is an error because I cannot write list of string directly on serial

This is my code:

import datetime
import time
import sys
import serial

date = datetime.datetime.now()
dateStr = str(date.strftime('%d-%m-%Y'))
unixTime = int(time.time())
crc = str("1234")


packet = list()

packet.append('test')
packet.append(dateStr)
packet.append(unixTime)
packet.append('4')
packet.append('81')
packet.append('1')
packet.append('0')

packet.append('00.7')
packet.append('4')
packet.append('9')
packet.append('0')

packet.append('18.8')
packet.append('5')
packet.append('3')
packet.append('0')

packet.append('15.3')
packet.append('4')
packet.append('6')
packet.append('0')

packet.append('2')
packet.append('0')
packet.append('13')
packet.append('0')

packet.append('0')
packet.append('0')
packet.append('185.6')

# add semicolon between list elements
serialCOM.write(packet)

Is there a way to concatenate each list elements into a list or bytearray?

Furthermore I need to add a semicolon between each list elements.

Thanks for the help!

asked Oct 17, 2016 at 12:41

3

If you want an actual bytearray object, pass the list into the bytearray constructor.

serialCOM.write(bytearray(packet))

Note that unixTime is not converted to a string so you must convert that first.

But what you probably want (based on the comment about semicolons) is to just join the strings using the join method of a string like this:

# Force all items in the list to be strings
msg = ';'.join(map(str,packet))
serialCOM.write(msg)

The result of the join is then:

In[50]: ';'.join(map(str,packet))
Out[50]: 'test;17-10-2016;1476708605;4;81;1;0;00.7;4;9;0;18.8;5;3;0;15.3;4;6;0;2;0;13;0;0;0;185.6'

answered Oct 17, 2016 at 12:54

Python list of strings to bytes

frmdstryrfrmdstryr

18.7k3 gold badges37 silver badges30 bronze badges

2

Educative Answers Team

A byte object is a sequence of bytes. These byte objects are machine-readable and can be directly stored on the disk. Strings, on the other hand, are in human-readable form and need to be encoded so that they can be stored on a disk.

There are several different types of encodings that can map text to the disk. The most popular ones are the​ ASCII and UTF-8 encoding techniques. ​

Convert strings to bytes

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument.

Printing the object shows a user-friendly textual representation, but the data contained in it is​ in bytes.

string = "Hello World"

# string with encoding 'utf-8'

arr = bytes(string, 'utf-8')

arr2 = bytes(string, 'ascii')

print(arr,'\n')

# actual bytes in the the string

for byte in arr:

print(byte, end=' ')

print("\n")

for byte in arr2:

print(byte, end=' ')

RELATED TAGS

python

strings

bytes

convert

Copyright ©2022 Educative, Inc. All rights reserved

Given a byte string. The task is to write a Python program to convert this byte of string to a list of integers. 

Method 1: By using list() function

The list() function is used to create a list from the specified iterable taken as its parameter.

Syntax:

list([iterable])

Parameters: This function accepts a single parameter that is illustrated below:

  • iterable: This is the specified sequence that is going to be created as another list.

Return values: This function returns a new list created out of the given iterable passed as its arguments.

Example: Python program to a byte string to a list of integers

Python3

Output:

[71, 70, 71]

Method 2: By using for loop and ord() function

The ord() function is used to return the number representing the Unicode code of a specified byte character.

Syntax:

ord(character)

Parameters: This function accepts a single parameter which is illustrated below:

  • character: This is the specified byte string.

Return values: This function returns the number representing the Unicode code of a specified byte character.

Example: Python program to a byte string to a list of integers

Python3

S = "GFG is a CS Portal"

nums = []

for chr in S:

    nums.append(ord(chr))

print(nums)

Output:

[71, 70, 71, 32, 105, 115, 32, 97, 32, 67, 83, 32, 80, 111, 114, 116, 97, 108]

Method 3: By using from_bytes() function

The from_bytes() function is used to convert the specified byte string into its corresponding int values.

Syntax:

int.from_bytes(bytes, byteorder, *, signed=False)

Parameters: This function accepts some parameters which are illustrated below:

  • bytes: A byte object
  • byteorder: This parameter determines the order of representation of the integer value. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. Big byte order calculates the value of an integer in base 256.
  • signed: Its default value is False. This parameter Indicates whether to represent 2’s complement of a number.

Return values: This function returns an int equivalent to the given byte.

Example: Python program to a byte string to a list of integers

Python3

byte_val = b'\x00\x01'

int_val = int.from_bytes(byte_val, "big")

print(int_val)

Output:

1

Example 2: Python program to a byte string to a list of integers

Python3

byte_val = b'\xfc\x00'

int_val = int.from_bytes(byte_val, "big", signed="True")

print(int_val)

Output:

-1024

The time and space complexity of all the methods is same::

Time Complexity: O(n)

Auxiliary Space: O(n)


How do you convert strings to bytes?

Convert strings to bytes.
string = "Hello World".
# string with encoding 'utf-8'.
arr = bytes(string, 'utf-8').
arr2 = bytes(string, 'ascii').
print(arr,'\n').

What is Bytestring in Python?

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer. On the other hand, a character string, often just called a "string", is a sequence of characters.

How do I convert string to bit in Python?

Method #1 : Using join() + ord() + format() The combination of above functions can be used to perform this particular task. The ord function converts the character to it's ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string.

How many bytes is a string?

A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)