[英]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: Output 我需要:
>>> report_time
'time:(from:!%272019-10-01T20:28:50.088Z!%27,to:now))'
Output I have: Output 我有:
>>> report_time
'ime:(from:!%272019-10-01T20:28:50.088Z!%27,to:now)'
You put the "+1" on the wrong index.您将“+1”放在错误的索引上。 You need to pick up from the first find
location and go one character past the second to pick up the extra right parenthesis.您需要从第一个find
位置和go拾取第二个字符之后的一个字符以拾取额外的右括号。 This last needs even one more character (thanks to `smac89 for catching that).最后一个甚至需要一个字符(感谢 `smac89 捕捉到它)。
report_time = s[s.find("time:("):s.find("))") + 2]
Output: Output:
'time:(from:!%272019-10-01T20:28:50.088Z!%27,to:now))'
Alternatively use a regular expression, eg:或者使用正则表达式,例如:
import re
re.search(r'(time:\(.*\)\))', s).group(1)
Explanation: group(1) returns the matching content of the 1st set of parentheses.说明:group(1) 返回第一组括号的匹配内容。 .* matches any characters in between. .* 匹配中间的任何字符。 The parentheses in your search therm need to be escaped.您的搜索热中的括号需要转义。
Output: Output:
'time:(from:!%272019-10-01T20:28:50.088Z!%27,to:now))'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.