I want to split a list of items with specific symbol.
I have used the following code
data = "launch, 7:30am, watch tv, workout, snap, running, research study and learn"
items = data.split(',')
print(', '.join([items[0], items[-1].split('—')[1]]))
Here what I wanted is that to split this data and print like this:
launch, study and learn
but a problem appears when data changed like this:
data = "launch, 7:30am, watch tv, workout, snap, running, research — discussion, study and learn"
items = data.split(',')
print(', '.join([items[0], items[-1].split('—')[1]]))
and in this I case I expected to get this result:
launch, discussion, study and learn
as such, an error appears "list index out of range"! that is right because there is no symbol "-" after last element, because of "," and I instructed data to be splitted as "," therefore in "discussion, study and learn" will be treated as separate data so an error appears. I wanted to not rewrite any code, is it possible to use code reuse to read both data. is it possible to read after "-" symbol?
Seems like your expected output is dependent on word research
We can implement the same using regex which will search research
word and gives you characters after it.
You can try this -
# -*- coding: utf-8 -*-
import re
(re.split(r'*research[^A-Za-z0-9]+',data))[-1]
#study and learn
#discussion, study and learn
Full Code:
# -*- coding: utf-8 -*-
import re
print ("{0}, {1}".format(data.split(',')[0], (re.split(r' *research[^A-Za-z0-9]+',data))[-1]))
#launch, study and learn
#launch, discussion, study and learn
Read more about python Regex :
https://docs.python.org/3/library/re.html
or about expressions here :
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.