Re: Using repr() with escape sequences



nummertolv wrote:
- Consider a string variable containing backslashes.
- One or more of the backslashes are followed by one of the letters
a,b,f,v or a number.

myString = "bar\foo\12foobar"

How do I print this string so that the output is as below?

bar\foo\12foobar

typing 'print myString' prints the following:

bar oo
foobar

and typing print repr(myString) prints this:

'bar\x0coo\nfoobar'


The interpretation of escape sequences happens when the Python compiler reads the string "bar\foo\12foobar". You'll see that when you do something like
>>> map (ord, "bar\foo\12foobar")
[98, 97, 114, 12, 111, 111, 10, 102, 111, 111, 98, 97, 114]
This displays the ASCII values of all the characters.

If you want to use a string literal containing backslashes, use r'' strings:
>>> myString = r'bar\foo\12foobar'
>>> map (ord, myString)
[98, 97, 114, 92, 102, 111, 111, 92, 49, 50, 102, 111, 111, 98, 97, 114]
>>> print myString
bar\foo\12foobar
>>> print repr (myString)
'bar\\foo\\12foobar'

If you get the strings from an external source as suggested by your original post, then you really have no problem at all. No interpretation of escape sequences takes place when you read a string from a file.

Daniel
.



Relevant Pages

  • Re: how do i import a text file with line wraps into a table
    ... Dim Directory As String ... Dim MyString As String ... Set dbs = CurrentDb ...
    (microsoft.public.access.externaldata)
  • Re: how do i import a text file with line wraps into a table
    ... Dim dbs As Database, rst As Recordset ... Dim Directory As String ... Dim MyString As String ... Set dbs = CurrentDb ...
    (microsoft.public.access.externaldata)
  • Re: how do i import a text file with line wraps into a table
    ... Dim dbs As Database, rst As Recordset ... Dim Directory As String ... Dim MyString As String ... Set dbs = CurrentDb ...
    (microsoft.public.access.externaldata)
  • Re: Email Merge in Word
    ... WHERE mystring is not null AND trim'' ... If the address looks blank but len) is> 0 then the field probably contains invisible non-space characters. ... Different software packages can treat "null", "a string set to ''", and "a string containing white space differently, and may also treat variable-length and fixed-length data differently in this respect. ...
    (microsoft.public.word.mailmerge.fields)
  • Re: Creating a derived object from a base object
    ... namespace MyString ... public class MyString ... private String _s; ... can't cast the result to a MyString since I can't cast a base type to ...
    (microsoft.public.dotnet.languages.csharp)