By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,462 Members | 1,057 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,462 IT Pros & Developers. It's quick & easy.

convert string to raw string?

P: n/a
Phd
Hi,

I'm writing a regex related program that lets the user supplies the
regex definition. Is there an easy way to convert a string into a raw
string?
Cheers
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a

"Phd" <py****@shaw.ca> wrote in message
news:39Usd.439257$nl.135440@pd7tw3no...
Hi,

I'm writing a regex related program that lets the user supplies the regex
definition. Is there an easy way to convert a string into a raw string?


There ain't no such thing as raw strings. Just 'raw' string *literals*,
where 'raw' denotes a mode for converting the literal in the code (which is
*not* a Python string) into a Python string.

Perhaps what you want is something like eval("r'%s'" % (raw_input(),)),
assuming no ' or " in user input.

Terry J. Reedy

Jul 18 '05 #2

P: n/a
Phd wrote:
I'm writing a regex related program that lets the user supplies the
regex definition. Is there an easy way to convert a string into a raw
string?


A raw string is a feature of the syntax of Python. Python gives you several
ways to write strings: single quoted, double quoted, triple single, triple
double, and raw versions of these. Once parsed from the source all of these
simply become objects of type 'str'.

The unicode modifier on a string does produce a different type of object
internally (type 'unicode'), but the raw modifier does not.

So, perhaps you would like to clarify what you really want to do? Perhaps
give an example?

If you are getting input from the user, then unless you are doing some
processing on it to interpret escape sequences the chances are you already
have what you need to use as a regular expression. If you *are*
interpreting escape sequences then the answer is you need to not do that
since the operation isn't really reversible.

Jul 18 '05 #3

P: n/a
Duncan Booth wrote:
If you are getting input from the user, then unless you are doing some
processing on it to interpret escape sequences the chances are you already
have what you need to use as a regular expression. If you *are*
interpreting escape sequences then the answer is you need to not do that
since the operation isn't really reversible.


If you are interpreting escape sequences, you probably want
string.decode or string.encode:
'\\n\\r'.decode('string_escape') '\n\r' '\n\r'.encode('string_escape')

'\\n\\r'

Steve
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.