String substitution -- reactions?

S

sdd

Here's a sample of how to do string substitution for a string with
double quotes around the names to be substituted. The following
is 2.3 code, but 2.2 code is also listed in the recipe at:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231347

def dequote(text, dictionary):
"""Replace quoted parts of string with dictionary entries."""
parts = text.split('"')
parts[1::2] = [dictionary[word] for word in parts[1::2]]
return ''.join(parts)

So, dequote('''Dear "user", we here at "provider" want to ....''',
dict(user='Resident', provider='Att.Net'))
can be used to fill out forms (or prepare html pages). If you need
to be able to include double quotes, simply make sure that the
dictionary provided get an entry like the one in {'':'"'}, then
using doubled double quotes may be used to represent quote marks,
as is common in a number of languages.

-Scott David Daniels
(e-mail address removed)
 
D

Diez B. Roggisch

def dequote(text, dictionary):
"""Replace quoted parts of string with dictionary entries."""
parts = text.split('"')
parts[1::2] = [dictionary[word] for word in parts[1::2]]
return ''.join(parts)

Sheeesh - thats cool! I don't wanna event think of how much code this would
need in java - _with_ a regexp-package. Not to mention with the builtin
string manipulating "capabilities".

And its actually the first example of the slice-step-argument I've seen -
which doesn't mean much, but I always asked myself what use they had.

Regards,

Diez
 

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

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top