scate636
scate636

Reputation: 135

Canonical Request \n Python 3

Ive been trying to figure this out all night with no luck. Im assuming that this will be a simple question for the more experienced programmer. Im working on a canonical request that I can sign. something like this:

canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers

However when I print(canonical_request) I get:

method
canonical_uri
canonical_querystring
canonical_headers

But this is what im after:

method\ncanonical_uri\ncanonical_querystring\ncanonical_headers

By the way Im using python34, I would really appreciate the help.

Upvotes: 0

Views: 288

Answers (2)

Kasravnd
Kasravnd

Reputation: 107307

As an alternative and more elegant way you can put your strings in a list and join them with escape the \n with add \ to leading :

>>> l=['method', 'canonical_uri', 'canonical_querystring', 'canonical_headers']
>>> print '\\n'.join(l)
method\ncanonical_uri\ncanonical_querystring\ncanonical_headers

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

Upvotes: 1

vicvicvic
vicvicvic

Reputation: 6244

So you want to not have "actual" newlines, but the escape character for newlines in your string? Just add a second slash to '\n' to escape it as well, '\\n'. Or prepend your strings with r to make them "raw"; in them the backslash is interpreted literally; r'\n' (commonly used for regular expressions).

canonical_request = method + r'\n' + canonical_uri + r'\n' + canonical_querystring + r'\n' + canonical_headers

For information about string literals, see String and byte literals in the docs.

Upvotes: 2

Related Questions