Insert variable into text search string

K

Kevin Glover

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? I am using Python 2.7.
 
M

MRAB

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? I am using Python 2.7.
Try string concatenation:

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

Jussi Piitulainen

Kevin said:
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? I am using Python 2.7.

Format is the right word: look up the .format method of strings.
'"of the kangaroo\'s"'

That's with Python 2.7.3. An older mechanism uses the percent sign for
place holders and as an operator.
 
C

Chris Angelico

Thank you both so much. I had tried % but not successfully.

To do it with %, just do this:

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

Use either that or .format(), whichever you like - both are fully
supported, and they have different strengths.

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,838
Latest member
KandiceChi

Latest Threads

Top