How To Split Serial Data In Python

In this tutorial, we will learn how to split serial data in Python. Serial data is commonly used in communications and networking where data transmission often happens through a sequence of symbols, such as bytes or characters.

Splitting serial data is useful in cases where you need to extract specific information or organize the data in a particular format. In Python, we have various techniques for splitting serial data, and in this tutorial, we will explore some of them using built-in string methods as well as the re (regular expressions) module.

Step 1: Split Serial Data using str.split() Method

The str.split() method is a built-in Python method for strings that splits a string based on a specified delimiter. If the delimiter is not provided, the default delimiter is whitespace.

Here is an example of splitting serial data using str.split():

Output:

['10', '30', '15', '20', '12']

As you can see, the data is now separated using the specified delimiter and stored as a list of strings.

Step 2: Split Serial Data using Regular Expressions

In some cases, you need more flexibility in terms of splitting patterns. In those instances, you can use Python’s **re (regular expressions) module** to split the serial data. The re.split() method allows you to split the data based on a regular expression pattern.

Here is an example of splitting serial data using re.split():

Output:

['10', '30', '15', '20', '12']

In this example, we used multiple delimiters(‘;|:|,|\|’) to split the serial data. The result is a list of strings.

Step 3: Post-processing the Splitted Data

Once you have split the data, you may need to further process it, such as converting it to the desired data type or applying additional filtering based on your requirements.

In the following example, we will convert the split data (currently a list of strings) to integers:

Output:

[10, 30, 15, 20, 12]

Full Code:

Conclusion

In this tutorial, we learned how to split serial data in Python using two methods: the built-in str.split() method and the more powerful re.split() method provided by the re (regular expressions) module.

Additionally, we discussed how to perform post-processing on splited data to achieve the desired output format. These techniques are helpful when working with data transmission, processing, and manipulation in Python.