Making a string raw

Brett Cannon bac at OCF.Berkeley.EDU
Tue Dec 4 17:06:21 EST 2001


Go to the Python Cookbook at activestate.com .  I posted a function there
that does exactly what Gary suggests you do.  It is under the tet section.
You could also just search for 'raw string' to find it.

-Brett Cannon



On Tue, 4 Dec 2001, Gary Herron wrote:

> There is no such thing as a raw string!  A string is a string is a
> string (except for unicode strings) and it might, or might not,
> contain back-slashes or non-ascii characters.
>
> The 'raw' part has to do with string literals, which is how create
> strings in a python program.  Other ways of creating strings, such as
> a Tkinter textbox, may or may not have an easy way to create string
> values with various special characters.  (If memory serves, a '\n' in
> a tkinter textbox produces a two character string -- backslash
> followed by "n".)
>
> Example:
>   spam = r'hello'
>   eggs = 'hello'
> produce exactly the same string value.  Neither is raw or un-raw, and
> both are Python strings with five characters.
>
> The same hold true for the following two  ways of creating strings:
>   spam = r'C:\abc'
>   eggs = 'C:\\abc'
> Again the two strings have the same value, neither is raw or not raw,
> and both have a backslash
>
> If what you want is to take a string which has various backslash
> sequences such as "\n" and convert such sequences into newlines, then
> try:
>   str.replace("\\n", "\n")
> or
>   str.replace(r"\n", "\n")
> both of which specify replacing the two character string backslash-"n"
> with a one character newline.
>
> Hope that's all clear,
> Gary Herron
>
>
> On Tuesday 04 December 2001 10:14 am, Rune Nesheim wrote:
> > Could any of you lot tell me how to convert a string stored in
> > avariable to a raw string?
> >
> > I know I create a raw string this way:
> >
> > spam = R'hello'
> >
> > But if I don't know what the string is going to contain, for example
> > if I fetch from a Tkinter text-box to the variable 'eggs' and want to
> > convert 'eggs' into a raw string.
>
>




More information about the Python-list mailing list