constructing binary \n

S

Steven Arnold

Is there a more elegant way to construct \[a-z] in a string than
something like:

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

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'.

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

steve
 
J

Jeff Shannon

Steven said:
Is there a more elegant way to construct \[a-z] in a string than
something like:

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

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'.


No, you actually *do* have '\n', the single byte that represents ASCII
linefeed.
Traceback (most recent call last):
.... print ord(char)
....
92
110
Note that '\n' is a single byte, while '\\n' is two bytes. In the first
case, '\n' is interpreted as the single LF byte. In the second case,
'\\' collapses into a single backslash, giving you a backslash byte and
a 'n' byte.

When you type a string literal containing a backslash, if that backslash
can combine with the following character to make a valid escape code, it
*will* do so unless you've explicitly turned off escaping (by, e.g.,
using raw strings). Of course, if the combination is *not* a valid
escape code, then the backslash and following character will be
interpreted normally.

Jeff Shannon
Technician/Programmer
Credit International
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top