convert string to raw string?

P

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
 
T

Terry Reedy

Phd said:
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
 
D

Duncan Booth

Phd said:
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.
 
S

Steven Bethard

Duncan said:
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'

Steve
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top