【问题标题】:How can I split a string into 2 strings using a delimiter如何使用分隔符将字符串拆分为 2 个字符串
【发布时间】:2018-09-10 13:25:59
【问题描述】:

字符串在字符串列表中,我想在? 字符上进行拆分。

例如,将['foo? bar\n', 'baz\n'] 拆分为['foo\n', 'bar\n', 'baz\n']

(我刚刚编辑了这个问题以包含换行符。)

【问题讨论】:

  • foo = ["foo ? bar", "baz"]; bar = [foo[0].split("?"), "baz"]
  • 列表理解方式:x = ['foo? bar', 'baz']; res = [j for i in x for j in i.split('?')]
  • 您能否更具体地了解 \n 和空间要求?第一项是否去除了前导空格并添加了换行符?每个拆分结果的末尾是strip() + \n 吗?

标签: python string list split delimiter


【解决方案1】:

你可以试试这个方法:

df=['foo? bar\n', 'baz\n']


new_list=[]
for i in df:
    if '?' in i:
        spli_data=i.split('?')
        for sub_ in spli_data:
            if '\n' not in sub_:
                new_list.append(sub_+'\n')
            else:
                new_list.append(sub_)

    else:
        new_list.append(i)

输出:

['foo\n', ' bar\n', 'baz\n']

【讨论】:

    【解决方案2】:

    看一个更明确的例子,也许更容易理解。

    def split_text(input_list):
        result = []
        # iterate through every string from input_list
        for item in input_list:
            #split a string by '? '; splitted is a list with minimum 1 element(item) when item does not contain '? '
            splitted = item.split('? ')
            # iterate through this list and append every string at result list
            for i in splitted:
                result.append(i)
        return result
    
    input_list = ['foo? bar', 'baz']
    print(split_text(input_list))
    

    【讨论】:

      【解决方案3】:

      当使用 generator 时,这相当简单:

      代码:

      def split_str_in_list(a_list, split_char):
          for big_str in a_list:
              for s in big_str.split(split_char):
                  yield s
      

      测试代码:

      print(list(split_str_in_list(['foo? bar', 'baz'], '? ')))
      

      结果:

      ['foo', 'bar', 'baz']
      

      【讨论】:

        【解决方案4】:

        这是一种方式。

        from itertools import chain
        
        x = ['foo? bar', 'baz']
        
        res = list(chain.from_iterable(i.strip().split('?') for i in x))
        
        # ['foo', ' bar', 'baz']
        

        【讨论】:

          猜你喜欢
          • 2015-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-29
          • 1970-01-01
          • 2016-04-06
          • 2012-02-14
          • 1970-01-01
          相关资源
          最近更新 更多