Dan
Dan

Reputation: 12705

Does "\n" get immediately converted to a newline charachter in python?

I'm using matplotlib, and I want to label something with "$\nu$". I was getting errors, and I realized it was because matplotlib was interpreting the \n as a newline. Does python immediately convert any instances of \n to newlines whenever a string is created?

Upvotes: 1

Views: 179

Answers (2)

aIKid
aIKid

Reputation: 28302

Yes. Except if you specified that it's a raw string:

r"$\nu$"

Another way around is to use double backslashes, escaping the backslash:

"$\\nu$"

Upvotes: 3

abarnert
abarnert

Reputation: 365975

As the Tutorial section on Strings and the reference documentation for String and Bytes literals explain, backslash escapes are interpreted in string literals.

This happens before matplotlib even gets to see anything; the literal "$\nu$" represents a string with a dollar sign, a newline, a u, and a dollar sign, and that string is the value matplotlib will see.

There are two ways to avoid this:

  • Escape the backslash itself, as in "$\\nu$".
  • Use a raw string, as in r"$\nu$".

Generally, when you're dealing with strings that have lots of backslashes (regular expressions, Windows pathnames, etc.), raw strings are more readable.

Upvotes: 7

Related Questions