splitting a string based on tab in the file

后端 未结 5 1397
迷失自我
迷失自我 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 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']
    

提交回复
热议问题