Reputation: 219
I've list of string like below:
12345,abcd,03/03/2013,23,,32,EURRIE-373HFJ-DJDMKD|838383,ldof,09/02/2017,23,,32,DJJFJF-DJFH83-JDUEJD|939393,uejs,08/07/2016,23,,32,JDJFJF-UEJDKD-LEPEKD|
My code:
content = "12345,abcd,03/03/2013,23,,32,EURRIE-373HFJ-DJDMKD|838383,ldof,09/02/2017,23,,32,DJJFJF-DJFH83-JDUEJD|939393,uejs,08/07/2016,23,,32,JDJFJF-UEJDKD-LEPEKD|"
result = [content.split(',')[2] for content in content.split('|')]
for v in result[:-1]:
print v
I want to print all second index element which is
03/03/2013
09/02/2017
08/07/2016
But I'm getting out of range error, what i'm doing wrong here.
Can someone help to fix this issue
Upvotes: 0
Views: 82
Reputation: 886
You can use re
:
import re
content = "12345,abcd,03/03/2013,23,,32,EURRIE-373HFJ-DJDMKD|838383,ldof,09/02/2017,23,,32,DJJFJF-DJFH83-JDUEJD|939393,uejs,08/07/2016,23,,32,JDJFJF-UEJDKD-LEPEKD|"
result = re.findall('\d{2}/\d{2}/\d{4}', content)
Result:
for date in result:
print date
# 03/03/2013
# 09/02/2017
# 08/07/2016
Also you can fix your code by filtering out empty elements after the 1st split:
result = [content.split(',')[2] for content in content.split('|') if len(content)]
Result:
for v in result:
print v
# 03/03/2013
# 09/02/2017
# 08/07/2016
Upvotes: 1
Reputation: 61
When I tested your code, I found that content.split('|') was generating an empty last element that was responsible for the index error after the split. So I changed it for:
[content.split(',')[2] for content in content.split('|')[:-1]]
and got:
['03/03/2013', '09/02/2017', '08/07/2016']
Does that solve the issue for you?
Upvotes: 2