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

Bill Felton subscriptions at cagttraining.com
Fri Jan 7 14:08:39 CET 2011


On Jan 7, 2011, at 7:47 AM, Tommy Kaas 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,
>  
>  
WARNING:  Just a beginner here, but...
The problem looks to me to be this:
"(.*)name(.*)"
is a literal string, so Python never "sees" the variable to get the value.  You can test this by copying your argument string into the shell and evaluating it.
Since you want the value of the variable, not the name, try this:
"(.*)"+name+"(.*)"

There may be other issues, but that should get you the string you want.  (Again, you test this expression before use to verify that it does what you want, just assign a string variable to 'name' before testing.)


regards,
Bill

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110107/21b0c7be/attachment-0001.html>


More information about the Tutor mailing list