Reputation: 747
I've been looking over some github repos of python scrapy spiders. In this repo I found the following lines of code:
FIRSTPAGE_URL_SYNTAX = 'http://%s.tumblr.com'
OTHERPAGE_URL_SYNTAX = 'http://%s.tumblr.com/page/%s'
name = "tumblr"
According to the documentation and SO thread that I've found, %s
requires an in-line reference to a variable. As you can see the code above contains no such reference. Is this working code? Why?
Upvotes: 1
Views: 157
Reputation: 184395
Those are just strings. All characters, including %s
, are valid in strings. The requirement for a substitution value comes when you use the %
operator, which they're not doing here. They're declaring those strings as templates, and will substitute values into them later.
By declaring them all in one place like that, it makes it easier to find them and change them. It's good coding practice.
Upvotes: 2
Reputation: 2164
Those variables serve as a template. Later in the code, you'll see something like
FIRSTPAGE_URL_SYNTAX % user
or
OTHERPAGE_URL_SYNTAX % (user, page)
You can do the same thing with {}
in strings:
template = "{} blah blah {}"
print(template.format(s1, s2))
This allows for a user to easily repeatedly use this one variable, if they need to reference multiple URLs with similar bodies, as opposed to having to retype the entire URL every time.
Upvotes: 6