How to Split a String by Tabs in Python?

Estimated read time 2 min read

You can split a string by tabs specifically in Python by using the split() method with the tab character (\t) as the argument. Here’s an example:

string = "John\tDoe\t25"
fields = string.split('\t')

print(fields)  # ['John', 'Doe', '25']

In this example, we create a string that contains three fields separated by tabs. We then call the split() method on the string, and pass the tab character (\t) as the argument to the method. This splits the string by tabs, and returns a list of fields. We assign this list to the variable fields, and print it to the console.

Note that if the string contains multiple whitespace characters (including tabs, spaces, and newlines), you can still use the split() method with no arguments to split the string by any whitespace character. For example:

string = "John   Doe\n25"
fields = string.split()

print(fields)  # ['John', 'Doe', '25']

In this example, we create a string that contains three fields separated by spaces and a newline character. We call the split() method on the string with no arguments, which splits the string by any whitespace character (including tabs, spaces, and newlines). This returns a list of fields, which we assign to the variable fields, and print to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply