I am trying to split a python string when a particular character appears.
For example:
mystring="I want to eat an apple. \n 12345 \n 12 34 56"
The output I want is a string with
[["I want to eat an apple"], [12345], [12, 34, 56]]
I am trying to split a python string when a particular character appears.
For example:
mystring="I want to eat an apple. \n 12345 \n 12 34 56"
The output I want is a string with
[["I want to eat an apple"], [12345], [12, 34, 56]]
>>> mystring.split(" \n ")
['I want to eat an apple.', '12345', '12 34 56']
If you specifically want each string inside its own list:
>>> [[s] for s in mystring.split(" \n ")]
[['I want to eat an apple.'], ['12345'], ['12 34 56']]
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)
Output:
['I want to eat an apple.', '12345', '12 34 56']
Use split(),strip() and re for this question
First split the strings by nextline and then strip each of them and then extract numbers from string by re, if length is more than one then replace the item
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']]