To split a string by tab in Python, you can use the Python string split() function and pass ‘\t’ to get a list of strings.
string = "This is a\tstring with\ttab in it"
print(string.split("\t"))
#Output:
["This is a", "string with", "tab in it"]
You can also use the split() function from the re (regular expression) module.
import re
string = "This is a\tstring with\ttab in it"
print(re.split("\t", string))
#Output:
["This is a", "string with", "tab in it"]
When working with strings and text in Python, the ability to manipulate and create new objects from strings can be useful.
One such situation is if you have tab characters in your strings and want to get the substrings between the tab characters.
To split a string by tab in Python, you can use the Python string split() function and pass ‘\t’ to get a list of strings.
Below is a simple example showing you how you can use split() to split a string by tab into a list of strings.
string = "This is a\tstring with\ttab in it"
print(string.split("\t"))
#Output:
["This is a", "string with", "tab in it"]
Splitting by Tab with re.split() Function in Python
Another way you can split a string by tabs is to use the regular expression module split() function to perform a regular expression which will find the “\t” characters and then create a list of strings.
Below is a simple example showing you how you can use re.split() to split a string by tab into a list of strings in Python.
import re
string = "This is a\tstring with\ttab in it"
print(re.split("\t", string))
#Output:
["This is a", "string with", "tab in it"]
Splitting String When There are More than One Tavin Python
Many times, you have more than one lines which you want to get rid of or deal with. With the re module, you can pass ‘\t+’ to re.split() and split a string which has multiple tab characters.
Below is a simple example showing you how to split a string with multiple tab characters.
import re
string = "This is a\t\tstring with\t\t\t\ttab in it"
print(re.split("\t+", string))
#Output:
["This is a", "string with", "tab in it"]
Hopefully this article has been useful for you to learn how to split a string by tab in Python.
Leave a Reply