0

In the given example: "\info\more info\nName" how would I turn this into bytes

I tried using unicode-escape but that didn't seem to work :(

data = "\info\more info\nName"
dataV2 = str.encode(data)
FinalData = dataV2.decode('unicode-escape').encode('utf_8')
print(FinalData)

This is were I should get b'\info\more info\nName' but something unexpected happens and I get DeprecationWarnings in my terminal I'm assuming that its because of the backslashes causing a invalid sequence but I need them for this project

  • The short answer is to use a raw string literal. I'm sure there's a good duplicate already on Stack Overflow, I'm just looking to find one. – Daniel Pryden Feb 08 '19 at 01:42

2 Answers2

1

Backslashes before characters indicate an attempt to escape the character that follows to make it into a special character of some sort. You get the DeprecationWarning because Python is (finally) going to make unrecognized escapes an error, rather than silently treating them as a literal backslash followed by the character.

To fix, either double your backslashes (not sure if you intended a newline; if so, double double the backslash before the n):

data = "\\info\\more info\\nName"

or, if you want all the backslashes to be literal backslashes (the \n shouldn't be a newline), then you can use a raw string by prefixing with r:

data = r"\info\more info\nName"

which disables backslashes interpolation for everything except the quote character itself.

Note that if you just let data echo in the interactive interpreter, it will show the backslashes as doubled (because it implicitly uses the repr of the str, which is what you'd type to reproduce it). To avoid that, print the str to see what it would actually look like:

>>> "\\info\\more info\\nName"  # repr produced by simply evaluating it, which shows backslashes doubled, but there's really only one each time
"\\info\\more info\\nName"
>>> print("\\info\\more info\\nName") # print shows the "real" contents
\info\more info\nName
>>> print("\\info\\more info\nName") # With new line left in place
\info\more info
Name
>>> print(r"\info\more info\nName") # Same as first option, but raw string means no doubling backslashes
\info\more info\nName
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

You can escape a backslash with another backslash.

data = "\\info\\more info\nName"

You could also use a raw string for the parts that don't need escapes.

data = r"\info\more info""\nName"

Note that raw strings don't work if the final character is a backslash.

gilch
  • 10,813
  • 1
  • 23
  • 28