[Tutor] variabel from raw input into re.search?

Wayne Werner waynejwerner at gmail.com
Fri Jan 7 14:07:55 CET 2011


On Fri, Jan 7, 2011 at 6:47 AM, Tommy Kaas <tommy.kaas at kaasogmulvad.dk>wrote:

> I try to write a program, where the user can write a word or a name and I
> will tell how many times the subject was mentioned in a text, I’m hosting.
>
> I guess it’s possible but not this way it seems?
>
> The re is only searching for the word “name” and not the variable name
>
> I’m using Python 2.6.6.
>
> TIA
>
> Tommy
>
>
>
> import re
>
> name = raw_input(’Who would you like to check’? ')
>
>
>
> mytxt = open("text.txt", "r")
>
> antal = []
>
> for line in mytxt:
>
>     if re.search("(.*)name(.*)", line):
>
>         antal.append(line)
>
> print name + ' was mentioned ' + str(len(antal)) + ' times in the text,
>

In Python, there is no such thing as variable interpolation, such as you'd
find in PHP or Perl. So when you type "(.*)name(.*)" (which I'm fairly sure
is the equivalent of r".*name.*", and also the equivalent search of "name"),
you literally have "name" in your string.

You have 3 options, string concatenation, and two styles of formatting:

>>> name = 'Sir Arthur'
>>> '.*' + name + '.*'
'.*Sir Arthur.*'
>>> '.*%s.*' % (name, )
'.*Sir Arthur.*'
>>> '.*{0}.*'.format(name)
'.*Sir Arthur.*'
>>> '.*{name}.*'.format(name=name)
'.*Sir Arthur.*'

The last two examples are different ways to accomplish the same thing.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110107/71b6dd91/attachment.html>


More information about the Tutor mailing list