I'm currently trying to print a string that usually comes before another string, for example "12/07/201911 : 00Type of Occurrence"
. Here I'm trying to print the time "11 : 00"
which always come before the text "Type of Occurrence"
.
I have tried this which print everything before the identifier. I would like to only print 7 characters before the identifier.
import re
A="12/07/2019 11 : 00Type of Occurrence"
print(A.split('Type of Occurrence', 1)[0].replace('.', '').upper())
It prints :
12/07/2019 11 : 00
Try this:
A="12/07/2019 11 : 00Type of Occurrence"
print(" ".join(A.split("Type of Occurrence")[0].split()[1:]))
OUTPUT :
11 : 00
Process :
A.split("Type of Occurrence")[0]
gives "12/07/2019 11 : 00"
"12/07/2019 11 : 00".split()[1:]
gives ['11', ':', '00']
" ".join(['11', ':', '00'])
gives 11 : 00
Try this :
>>> A="12/07/2019 11 : 00Type of Occurrence"
>>> i = A.find('Type of Occurrence')
>>> i
18
>>> A[i-7:i]
'11 : 00'
If the whitespaces between the colon can vary, you might use a capturing group for the time part and match Type of Occurrence:
((?:0[0-9]|1[0-9]|2[0-3])\s*:\s*[0-5][0-9])Type of Occurrence
Basic Idea:
A="12/07/2019 11 : 00Type of Occurrence"
A = A.split('Type of Occurrence', 1)[0].replace('.', '').upper()
A[-7:]
>>> '11 : 00'
Is this what you want?
I would like to only print 7 characters before the identifier.
You may use this regex:
>>> import re
>>> A="12/07/2019 11 : 00Type of Occurrence"
>>> print re.findall(r'(.{7})Type of Occurrence', A)[0]
11 : 00
re.findall
prints captured group if they are available in regex.
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.