【问题标题】:Split a python string by particular identifications [duplicate]按特定标识拆分python字符串[重复]
【发布时间】:2020-06-02 01:03:50
【问题描述】:

我正在尝试在出现特定字符时拆分 python 字符串。

例如:

mystring="I want to eat an apple. \n 12345 \n 12 34 56"

我想要的输出是一个带有

的字符串
[["I want to eat an apple"], [12345], [12, 34, 56]]

【问题讨论】:

  • mystring.split('\n')

标签: python string split


【解决方案1】:
>>> mystring.split(" \n ")
['I want to eat an apple.', '12345', '12 34 56']

如果您特别希望每个字符串都包含在自己的列表中:

>>> [[s] for s in mystring.split(" \n ")]
[['I want to eat an apple.'], ['12345'], ['12 34 56']]

【讨论】:

    【解决方案2】:
    mystring = "I want to eat an apple. \n 12345 \n 12 34 56"
    # split and strip the lines in case they all dont have the format ' \n '
    split_list = [line.strip() for line in mystring.split('\n')] # use [line.strip] to make each element a list...
    print(split_list)
    

    输出:

    ['I want to eat an apple.', '12345', '12 34 56']
    

    【讨论】:

      【解决方案3】:

      使用split()strip()re 回答这个问题

      先用nextline分割字符串,然后剥离它们,然后用re从字符串中提取数字,如果长度大于1则替换该项目

      import re
      mystring="I want to eat an apple. \n 12345 \n 12 34 56" 
      l = [i.strip() for i in mystring.split("\n")]
      for idx,i in enumerate(l):
        if len(re.findall(r'\d+',i))>1:
          l[idx] = re.findall(r'\d+',i)
      
      print(l)
      #['I want to eat an apple.', '12345', ['12', '34', '56']]
      

      【讨论】:

        猜你喜欢
        • 2014-07-22
        • 1970-01-01
        • 1970-01-01
        • 2015-12-18
        • 1970-01-01
        • 2021-03-05
        • 2014-12-08
        • 2020-10-03
        • 2023-03-23
        相关资源
        最近更新 更多