I have multiple stock names as follows
'ADANIENT29APR211120'
'AARTIIND29APR211360'
'ADANIPORTS29APR21730'
What I intend to do is to seperate the stock name, date, the price and print it as shown
'ADANIENT 29APR21 1120'
'AARTIIND 29APR21 1360'
'ADANIPORTS 29APR21 730'
Now i know about module known as datefinder which can help me to extract dates in python
I used it as follows:
import datefinder
string_with_dates = '''
ADANIENT29APR211120PE
'''
matches = datefinder.find_dates(string_with_dates)
for match in matches:
print(match)
The output this gives me is
runfile('C:/Users/hozef/AppData/Local/Temp/untitled0.py', wdir='C:/Users/hozef/AppData/Local/Temp')
2021-04-29 21:11:20
My question is that using datefinder I extracted the date in the string now how do i extract the name and price of the particular stock from the input string
CodePudding user response:
Using re.findall
:
inp = ['ADANIENT29APR211120', 'AARTIIND29APR211360', 'ADANIPORTS29APR21730']
for x in inp:
parts = re.findall(r'^([A-Z] )(\d{2}[A-Z]{3}\d{2})(\d )$', x)[0]
print(' '.join(parts))
This prints:
ADANIENT 29APR21 1120
AARTIIND 29APR21 1360
ADANIPORTS 29APR21 730
The regex used here says to match:
^
([A-Z] ) stock name in all caps
(\d{2}[A-Z]{3}\d{2}) 2 digit day, 3 letter all caps month, 2 digit year
(\d ) integer price
$