Martin Bouhier
Martin Bouhier

Reputation: 173

How to find part of string?

I am working with a string. I could find the part of string I need but not all of it. Which part of my code needs to change?

s = "3D(filters:!!(),refreshInterval:(pause:!!t,value:0),time:(from:!%272019-10-01T20:28:50.088Z!%27,to:now))%26_a%3D(description:!%27!%27,filters:!!(),fullScreenMode:!!"

report_time = s[s.find("time:(") + 1:s.find("))")]

Output I need:

>>> report_time
'time:(from:!%272019-10-01T20:28:50.088Z!%27,to:now))'

Output I have:

>>> report_time
'ime:(from:!%272019-10-01T20:28:50.088Z!%27,to:now)'

Upvotes: 1

Views: 232

Answers (2)

HeyMan
HeyMan

Reputation: 1845

Alternatively use a regular expression, e.g:

import re
re.search(r'(time:\(.*\)\))', s).group(1)

Explanation: group(1) returns the matching content of the 1st set of parentheses. .* matches any characters in between. The parentheses in your search therm need to be escaped.

Output:

'time:(from:!%272019-10-01T20:28:50.088Z!%27,to:now))'

Upvotes: 0

Prune
Prune

Reputation: 77837

You put the "+1" on the wrong index. You need to pick up from the first find location and go one character past the second to pick up the extra right parenthesis. This last needs even one more character (thanks to `smac89 for catching that).

report_time = s[s.find("time:("):s.find("))") + 2]

Output:

'time:(from:!%272019-10-01T20:28:50.088Z!%27,to:now))'

Upvotes: 1

Related Questions