0

Normally I don't use backslashes in my strings because it complicates things. In this case I don't have a choice as a black slash \ is within a token ive been given and I'm trying to pass in a url request.

Here is an example of what I'm seeing, ive tried double quotes, using repr() , escaping it but the results still show either double \ or something that doesnt represent the key.

token ="ABC\$DEfg"
headers = {'content-type': 'application/json', 'Authorization': 'TOK:'+token+'', 'Accept': 'application/json'}

print ('Headers are = {0}'.format(headers))

Even though I used double quotes this is the result when I try to run the script above :

Headers are = {...'Authorization': 'TOK:ABC\\$DEfg'}

It should be ABC\$DEfg not ABC\$DEfg'

How best should I be inserting token into my request and maintain a normal single back slash. Also the token can change so I would like way to wrap the variable correctly

chowpay
  • 1,515
  • 6
  • 22
  • 44
  • `'\\'` is how Python represents a string with a single backslash. Thus, `'ABC\$DEfg'` is itself wrong (`\$` isn't meaningful in Python, but single backslashes should be used only in non-raw strings in cases like `\n` or `\t` where they're used as a stand-in for something else -- like a newline and a tab, in the above cases, respectively). – Charles Duffy Dec 03 '19 at 21:23
  • You can test this yourself; evaluate `"ABC\$DEfg" == 'ABC\\$DEfg'` and see that the result is true; Python is parsing the ambiguous `\$` into two characters, `'\\'` (which is, again, a two-character representation of a *one-character* string) and `'$'`. – Charles Duffy Dec 03 '19 at 21:25
  • @CharlesDuffy you're correct actually the $ is apart of the token provided. Are you saying that my request should still be correct even if it shows 2 \\s it is merely a py representation? – chowpay Dec 03 '19 at 21:27
  • Correct, the two backslashes are just how Python represents a single backslash in a regular string. In fact, if you `print('\\')`, you'll see only one backslash in the output (as `print(some_string)` writes the string itself, not its `repr()`esentation). – Charles Duffy Dec 03 '19 at 21:28

0 Answers0