0

These two lines are from a program that carries out a phrase search of Wikipedia and returns the total number of times that the specific phrase occurs. It is essential that the search contains an apostrophe:

results = w.search("\"of the cat's\"", type=ALL, start=1, count=1)
print results.total

I want to replace the word "cat" with a variable, e.g.

q = "cat"

so that I can generate the same search format for a list of different words. How do I format the search string to include the variable, please?

jramirez
  • 8,537
  • 7
  • 33
  • 46
  • This stringformatting questions have been asked many times. E.g. here http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format – deinonychusaur Feb 19 '14 at 19:41

2 Answers2

0

With Python you could simply do:

q = "cat"
results = w.search("\"of the " + q + "'s\"", type=ALL, start=1, count=1)
print results.total

There is also

q = "cat"
results = w.search("\"of the %s's\"" & q, type=ALL, start=1, count=1)
print results.total

And

q = "cat"
results = w.search("\"of the {query}'s\"".format(query=q), type=ALL, start=1, count=1)
print results.total

See this post for a more detailed discussion, including performance.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
Farmer Joe
  • 6,020
  • 1
  • 30
  • 40
0

First off, Python has some useful string methods that I feel would be very helpful to you. In this case we are going to be using the format function. Also, don't me intimidated by ' or "s. You can simply escape them with a backslash. Demo:

>>> a = '\''
>>> a
"'"

See how the single quote is sandwiched between those double quotes?

You can do the same with double-quotes:

>>> a = "\""
>>> a
'"'
>>> 

Now, to answer your question, you can use the .format function that comes with the string class (no imports necessary).

Lets have a look:

>>> a = "{}\'s hat"
>>> a.format("Cat")
"Cat's hat"
>>> a.format("Dog")
"Dog's hat"
>>> a.format("Rat") # Rats wear hats?
"Rat's hat"
>>> 

In your case, you can simply do this:

w.search("\"of the {}'s\"".format(<your animal here>), type=ALL, start=1, count=1)
Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199