splitting a string based on tab in the file

后端 未结 5 1390
迷失自我
迷失自我 2020-12-08 04:24

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.<

相关标签:
5条回答
  • 2020-12-08 04:57

    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...

    0 讨论(0)
  • 2020-12-08 05:01

    An other regex-based solution:

    >>> strs = "foo\tbar\t\tspam"
    
    >>> r = re.compile(r'([^\t]*)\t*')
    >>> r.findall(strs)[:-1]
    ['foo', 'bar', 'spam']
    
    0 讨论(0)
  • 2020-12-08 05:05

    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']
    
    0 讨论(0)
  • 2020-12-08 05:05

    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']  
    
    0 讨论(0)
  • 2020-12-08 05:12

    Split on tab, but then remove all blank matches.

    text = "hi\tthere\t\t\tmy main man"
    print [splits for splits in text.split("\t") if splits is not ""]
    

    Outputs:

    ['hi', 'there', 'my main man']
    
    0 讨论(0)
提交回复
热议问题