Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert regular Python string to raw string

Tags:

python

string

I have a string s, its contents are variable. I'd like to make it a raw string. How do I go about this?

Something similar to the r'' method.

like image 428
rectangletangle Avatar asked Dec 11 '10 04:12

rectangletangle


People also ask

How can we make a string a raw string?

In Python, when you prefix a string with the letter r or R such as r'...' and R'...' , that string becomes a raw string. Unlike a regular string, a raw string treats the backslashes ( \ ) as literal characters.

How do you create a raw string in Python?

Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.

How do you make a string not a string in Python?

Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). Since strings can't be changed, we construct *new* strings as we go to represent computed values.

What is a raw string?

A raw string in programming allows all characters in a string literal to remain the same in code and in the material, rather than performing their standard programming functions. Raw strings are denoted with the letter r, or capital R, and might look something like this: R “(hello)”


2 Answers

i believe what you're looking for is the str.encode("string-escape") function. For example, if you have a variable that you want to 'raw string':

a = '\x89' a.encode('unicode_escape') '\\x89' 

Note: Use string-escape for python 2.x and older versions

I was searching for a similar solution and found the solution via: casting raw strings python

like image 171
Jolly1234 Avatar answered Oct 14 '22 21:10

Jolly1234


Raw strings are not a different kind of string. They are a different way of describing a string in your source code. Once the string is created, it is what it is.

like image 42
Karl Knechtel Avatar answered Oct 14 '22 20:10

Karl Knechtel