通过特定标识拆分python字符串

时间:2020-06-02 01:03:50

标签: python string split

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

例如:

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

我想要的输出是带有

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

3 个答案:

答案 0 :(得分:4)

>>> 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']]

答案 1 :(得分:0)

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']

答案 2 :(得分:0)

对此问题使用split()strip()re

首先通过nextline分割字符串,然后剥离每个字符串,然后通过re从字符串中提取数字,如果长度大于一个,则替换该项目

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']]
相关问题