Split Strings by Tab in Python

Split Strings by Tab in Python

  1. Use Regex Method to Divide Given String by Tab in Python
  2. Use str.rstrip() and Regex Method to Divide Given String by Tab in Python

This tutorial explores different methods to split strings by tab in Python.

We will go over the following approaches for various scenarios.

  1. regex method
  2. str.rstrip + regex to get rid of trailing tab string

Let us consider a string in Python, which we will divide to demonstrate the split by tab.

line = "abc def ghi"

We will now divide the above string using the mentioned two approaches.

Use Regex Method to Divide Given String by Tab in Python

In this approach, we will be using the regex library for the split process.

import re

We will use the re.split() function in regex, where we pass our string, split with the regex pattern.

print(re.split(r' ', line))

The above code will divide the input string every time a tab occurs and insert the string element into a list. We get a list with all the string elements.

The above code would give the following output.

['abc', 'def', 'ghi']

Here we can see that we got the list of strings as desired. Let us consider a case where we have a tab at the end of our string.

Let us consider a new string with a trailing tab.

line1 = "abc def ghi "

Let us apply the same method on the new string and see the output.

print(re.split(r' ', line1))

The above code will give us the following output.

['abc', 'def', 'ghi','']

Here we get an empty string element at the end of the list, which is not required. We can avoid this using the next approach that we will see.

Use str.rstrip() and Regex Method to Divide Given String by Tab in Python

Consider the same string with the trailing tab in the last example. We will use the str.rstrip() function with regex to avoid adding an empty string element for the trailing tab in our list.

We run rstrip() function on our string before passing to the re.split() along with the regex pattern.

line1 = "abc def ghi "
print(re.split(r' ', line1.rstrip(' ')))

We will get the following output without an empty string element at the end.

['abc', 'def', 'ghi']

We can use this method to avoid getting an empty string element at the end of the list that we got in our previous method.

Thus, we can efficiently split strings by tab in Python with the above techniques.

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python