Python: getting finding a variable in a string
I currently have some code that goes to a URL, fetches the source code, and I'm trying to get it to return a variable from the string. So I created:
changetime = refreshsource.find('VARIABLE pm NST')
But it wouldn't find the area in the string because the word is not VARIABLE, it is something else. How would I retrieve the constantly changing VARIABLE from that s开发者_运维百科tring?
A regular expression will be able to achieve this for you. I'd you give some examples of what variable will be the we could come up with a strict expression. To match what you have above something like the following will do:
import re
# this will match 01:23, 11:34, 12:00, etc.
timex = re.compile('.*(\d{2}:\d{2})[ ]?pm NST')
match = timex.match(text, re.M|re.S)
variable = match.groups(0)
Edit: this code will actually work (unlike that first attempt :) ):
import re
# this will match 01:23, 11:34, 12:00, etc.
timex = re.compile('(\d{2}:\d{2})[ ]?pm NST')
match = timex.search(text)
if match:
variable = match.groups(0)
If the pattern is really that simple, then this seems a typical case where regular expressions comes quite handy.
Note: if you are new to regular expressions, you may want to use some introduction, like the http://www.regular-expressions.info.
On the other hand, if the pattern is more complex, then you may want to use an HTML parser, like for instance BeautifulSoup.
精彩评论