[Tutor] (no subject)
Sean 'Shaleh' Perry
shaleh at speakeasy.net
Tue Dec 23 20:15:26 EST 2003
On Tuesday 23 December 2003 15:19, arkamir at softhome.net wrote:
> Hello,
>
> I have a question concerning turning strings into variables.
>
> Say I have a list like x:
>
> x = ['hello', 'bye']
>
> What I need is the final result to look like this, or the equivelant of
> this. How would I do this???
>
> hello = re.compile(r'<!--INSERT HELLO HERE-->')
> bye = re.compile(r'<!--INSERT BYE HERE-->')
>
> I think it would look something like
>
> for y in x:
> #string to variable# = re.compile(r'<--INSERT %s HERE-->' % y)
>
> Is this the most effecient way,
hmm, perhaps I am not fully understanding you, but would this work?
transforms = { 'hello': '<!-- INSERT HELLO HERE -->', 'bye': '<!-- INSERT BYE
HERE -->' }
for y in x:
if y in transforms:
print transforms[y]
If this is not what you meant, how about specifying your needs by giving us
some sample input and output? For example if we start with:
Hello, World!
we should end up with:
<!-- Hello -->, World!
> and how would I convert y to capitols.
>>> name = 'bob'
>>> name.title()
'Bob'
>>> name.upper()
'BOB'
>
> Also can someone explain lambdas too me. Whenever I do something like:
>
in general you should stick to asking one type of question at a time. Makes
it easier for people to follow the thread and especially for people searching
the archives later on.
> x = lambda x: x + 1, (1)
>
> I get (<function whatever blah>, 2)
>
lambda is a way to generate small functions during execution instead of during
compilation / parsing. It is used most often for event handlers where the
action is usually simple and used once so defining a function would make the
program longer or harder to follow. People who like to program in a more
functional (instead of OO) style like to use it as well.
For instance:
for word in map(lambda y: y.upper(), x): # re-use you list from above
print word
Current python uses a different idiom:
for word in [ y.upper() for y in x ]:
print word
You can write plenty of python and never use lambda. Especially with python
2.2 and newer.
More information about the Tutor
mailing list