-1

I have some code in python like:

something = r"grep some {0} stuff".format("somethingelse")

r = subprocess.check_output(
    something, shell=True, cwd=os.path.join(directory, 'path'))

In essence, I want to know what the first assignment is doing with "r". If "r" has a value (assigned last), how is the first assignment able to use it successfully (r doesn't have a value yet)? What exact does the first line do when it uses "r"?

I know you guys will hate this question, but it's something that's very difficult to google for. Feel free to throw me a link to read and I'll be on my way.

Also, if I do:

test = r"wat"

in a completely separate script, the command will work. Then when you print "test", all it does it print "wat". What happens to the "r"?

Peter
  • 427
  • 2
  • 7
  • 22

1 Answers1

5

Putting r before a string literal designates it as a raw string literal, meaning that escape sequences are not processed (a backslash \ is just a backslash). It has nothing to do with the variable r that you use in the second line of your example.

Community
  • 1
  • 1
MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • Cheers. Can this be used against existing strings as well? If 'test = "something"', is it possible to assign r(test) ? – Peter Jul 11 '14 at 01:41
  • No, it's a constant modifier, it changes how literals are interpreted in the source code. It's not a function. – Max Jul 11 '14 at 01:42
  • @Peter it only exists because if you want the string literal `c:\system32` you have to enter `c:\\system32` or else Python thinks you're trying to use the `\ ` to escape the `s` (turning it into `['C', ':', '\s', 'y', 's', 't', 'e', 'm', '3', '2']`. However a string with the value `C:\system32` does not have any escaped characters, so that is unnecessary. – Adam Smith Jul 11 '14 at 02:04