Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting a string based on tab in the file

I have file that contains values separated by tab ("\t"). I am trying to create a list and store all values of file in the list. But I get some problem. Here is my code.

line = "abc def ghi" values = line.split("\t") 

It works fine as long as there is only one tab between each value. But if there is one than one tab then it copies the tab to values as well. In my case mostly the extra tab will be after the last value in the file.

like image 630
hjelpmig Avatar asked Jun 11 '13 07:06

hjelpmig


People also ask

How do I split a string into substring?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a string in a tab?

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

How do you print values which must be separated by tab space?

The easiest way to print a tab character in Python is to use the short-hand abbreviation '\t' . To see the tab spaced character in the REPL wrap any variable containing a tab character in the built-in print() function.


2 Answers

You can use regex here:

>>> import re >>> strs = "foo\tbar\t\tspam" >>> re.split(r'\t+', strs) ['foo', 'bar', 'spam'] 

update:

You can use str.rstrip to get rid of trailing '\t' and then apply regex.

>>> yas = "yas\t\tbs\tcda\t\t" >>> re.split(r'\t+', yas.rstrip('\t')) ['yas', 'bs', 'cda'] 
like image 185
Ashwini Chaudhary Avatar answered Sep 20 '22 05:09

Ashwini Chaudhary


You can use regexp to do this:

import re patt = re.compile("[^\t]+")   s = "a\t\tbcde\t\tef" patt.findall(s) ['a', 'bcde', 'ef']   
like image 34
DimmuR Avatar answered Sep 20 '22 05:09

DimmuR