constructing binary \n

Tim Peters tim.peters at gmail.com
Wed Sep 29 22:48:25 EDT 2004


[Steven Arnold]
> Is there a more elegant way to construct \[a-z]

What does that notation mean?  One concrete "before" and "after"
example would have done you more good here than everything else.

> in a string than something like:
> 
> s = '\\n'
> result = eval( "'%s'" ) % s

Sorry, that didn't help me understand what you're after.  To the
contrary, it hurt.  The last line there could have been replaced by:

    result = s

and done exactly the same thing:

>>> s = '\\n'
>>> result = eval( "'%s'" ) % s
>>> s == result
True

`s` and `result` are both the two-character string consisting of a
backslash followed by the letter `n`.  Is that what you want?  That
was also my best guess as to what the notation \[a-z] meant at the
start ("umm ... Steven wants a backslash, followed by a lowercase
letter?").

> Another ugly method would be to build a dict with all the different
> special letters I want as keys, and their corresponding values as
> values.  Or I could have a huge if/elif structure.  I can't make ord
> work, because while ord( '\n' ) gives me a reasonable integer that I
> can interpolate with %c, I don't have '\n', I have '\\n'.

Sorry, still not following.

>>> ord('\n')
10
>>> chr(10)
'\n'
>>> '%c' % 10
'\n'
>>> len(chr(10))
1
>>> len('%c' % 10)
1

I don't know why you say "I have '\\n'" after, presumably, doing

    '%c' % ord('\n')

either, since there's no sense I can see in which you would in fact
have '\\n' after doing that.  As the session above shows, you actually
have the one-character string consisting of a newline after doing
that.  But it's not clear whether that's what you want either.

> Is there a simple, graceful way to do this sort of translation?

Yes -- but until you can explain *which* transformation you're trying
to make, it's hard to tell you how to do it gracefully <wink>.



More information about the Python-list mailing list