splitting a string based on tab in the file
Question:
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.
Answers:
You can use regex
here:
>>> import re
>>> strs = "footbarttspam"
>>> 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 = "yasttbstcdatt"
>>> re.split(r't+', yas.rstrip('t'))
['yas', 'bs', 'cda']
You can use regexp to do this:
import re
patt = re.compile("[^t]+")
s = "attbcdettef"
patt.findall(s)
['a', 'bcde', 'ef']
Split on tab, but then remove all blank matches.
text = "hittheretttmy main man"
print([splits for splits in text.split("t") if splits])
Outputs:
['hi', 'there', 'my main man']
Python has support for CSV files in the eponymous csv
module. It is relatively misnamed since it support much more that just comma separated values.
If you need to go beyond basic word splitting you should take a look. Say, for example, because you are in need to deal with quoted values…
An other regex
-based solution:
>>> strs = "footbarttspam"
>>> r = re.compile(r'([^t]*)t*')
>>> r.findall(strs)[:-1]
['foo', 'bar', 'spam']
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.
You can use regex
here:
>>> import re
>>> strs = "footbarttspam"
>>> 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 = "yasttbstcdatt"
>>> re.split(r't+', yas.rstrip('t'))
['yas', 'bs', 'cda']
You can use regexp to do this:
import re
patt = re.compile("[^t]+")
s = "attbcdettef"
patt.findall(s)
['a', 'bcde', 'ef']
Split on tab, but then remove all blank matches.
text = "hittheretttmy main man"
print([splits for splits in text.split("t") if splits])
Outputs:
['hi', 'there', 'my main man']
Python has support for CSV files in the eponymous csv
module. It is relatively misnamed since it support much more that just comma separated values.
If you need to go beyond basic word splitting you should take a look. Say, for example, because you are in need to deal with quoted values…
An other regex
-based solution:
>>> strs = "footbarttspam"
>>> r = re.compile(r'([^t]*)t*')
>>> r.findall(strs)[:-1]
['foo', 'bar', 'spam']