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.
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.
Use str. rstrip() and Regex Method to Divide Given String by Tab in Python.
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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With