Reputation: 864
I would like to extract the values within parentheses and as well the word starting before it. For example, in a given text file, I would have the below details:
Total DB read time : TDBT(56) TDTO(78) TDTC(567) TON(567) TOT(345)
Expected output is a tuple or list:
TDBT 56 TDTO 78 TDTC 567 TON 567 TOT 345
Upvotes: 1
Views: 193
Reputation: 180391
split on :
and replace the ()
with spaces using str.translate
s = "Total DB read time : TDBT(56) TDTO(78) TDTC(567) TON(567) TOT(345)"
spl = s.split(":")[1].translate({ord("("):" ",ord(")"):" "}).split()
['TDBT', '56', 'TDTO', '78', 'TDTC', '567', 'TON', '567', 'TOT', '345']
Or use str.replace
:
s="Total DB read time : TDBT(56) TDTO(78) TDTC(567) TON(567) TOT(345)"
spl = s.split(":")[1].replace("("," ").replace(")"," ").split()
print(spl)
If you want pairs you can use re:
s="Total DB read time : TDBT(56) TDTO(78) TDTC(567) TON(567) TOT(345)"
import re
r = re.compile("(\w+)\((\d+)\)")
print(r.findall(s))
[('TDBT', '56'), ('TDTO', '78'), ('TDTC', '567'), ('TON', '567'), ('TOT', '345')]
Upvotes: 1