String literals: represent a line break

How to put a line break in a string literal: escape sequences versus multiline literal forms, LF versus CRLF, and what survives copying, JSON and HTML.

A line break inside a string can be written two ways. You can use an escape sequence such as \n, or you can type an actual line break inside a literal form that allows one. Both can produce the same runtime value. They differ in how the source reads, how it behaves when copied, and which destinations will interpret it. This review explains what each approach changes and when each one fits.

Is this approach suitable for your use?

  • Use the \n escape for short strings, single-line literals, and any data format that forbids raw control characters inside strings, such as JSON.
  • Use a multiline literal form (triple quotes, template literals, text blocks or raw strings) when the text spans several lines and should read in the source the way it will appear.
  • Use a plain text file or resource with real line breaks when non-developers edit the text, when it is long prose, or when it goes to a destination that will not interpret escape sequences.

The main tradeoff is this. An escape is compact and unambiguous about which character is stored, but it hides the layout. A literal line break shows the layout, but it introduces questions about indentation, line-ending conventions and invisible whitespace. Prefer plain text when people outside the code will read or edit the content, because escapes are source syntax and are not meant for those readers.

What the transformation actually changes

Separate the source representation from the stored value. When you write \n in source code, the file contains two characters, a backslash and the letter n. The compiler or interpreter turns them into one character, line feed (U+000A), in the runtime string. This changes the stored characters. It is not a visual effect. Whether the line feed appears as a new line depends on the program or display that later shows the string.

s = "a\nb"
len(s)    # 3: 'a', line feed, 'b'

r = r"a\nb"
len(r)    # 4: 'a', backslash, 'n', 'b'

The Python example above shows the difference. In an ordinary string, the escape is processed. In a raw string (the r prefix), escape processing is turned off, so the backslash and n remain two separate characters. Many languages have a similar raw form. If a raw string contains \n, it does not contain a line break.

Line feed, carriage return and CRLF

\n is line feed (LF, U+000A) and \r is carriage return (CR, U+000D). Unix-like systems conventionally end lines with LF. Windows text conventions and several network protocols, including HTTP and SMTP headers, use the CR LF pair. In C, writing \n to a stream opened in text mode can be translated to the platform convention on output, while binary mode writes it unchanged. Write the sequence the destination expects instead of assuming LF is universal.

Multiline literal forms by language

  • Python: triple-quoted strings can contain literal line breaks. Leading indentation on each line becomes part of the value. textwrap.dedent is a common way to remove it.
  • JavaScript: template literals (backticks) can contain literal line breaks, and the language specification normalizes CR and CRLF inside them to LF. Single- and double-quoted strings cannot contain an unescaped LF or CR.
  • Java: text blocks (triple quotes, standard since Java 15) span lines. They strip incidental indentation and trailing spaces and normalize line terminators to LF.
  • C#: verbatim strings (@ prefix) can span lines and keep the line endings the source file contains. C# 11 adds raw string literals delimited by three or more quotes.
  • Go: backtick raw strings span lines, perform no escape processing, and discard carriage returns.
  • C and C++: ordinary literals cannot span lines, but adjacent literals are concatenated, so each line can be a separate literal ending in \n. C++11 raw strings, written R"( ... )", can span lines.
  • Bash: ANSI-C quoting, written $'a\nb', interprets the escape. A plain double-quoted string can also contain a literal line break. echo treats \n differently across shells and options, so printf is the more consistent choice.

Things that look like line breaks but are not

In C, Python and JavaScript, a backslash at the end of a source line inside a string literal is a line continuation. It lets the source wrap but adds no character to the value. An escaped backslash written as \n produces a literal backslash followed by n, not a break. Unicode also defines LINE SEPARATOR (U+2028) and PARAGRAPH SEPARATOR (U+2029). These are different characters from LF. JavaScript treats them as line terminators, but many other tools do not, so they can cause inconsistent results.

In HTML, a line feed in normal text counts as whitespace and usually collapses into a space. A visible break needs either a br element or a CSS white-space value such as pre, pre-wrap or pre-line. That CSS affects presentation only and does not change the stored string. The reverse also holds: a string can contain correct line feeds and still display on one line because the destination ignores them.

Will the result remain readable and usable after copying or sharing?

The answer depends on whether you copy source syntax or the runtime value, and on whether the destination interprets escapes. If you paste a source literal containing \n into a chat, spreadsheet or form, the backslash and n usually appear literally, because those destinations do not process programming-language escapes. If you copy printed output, you get a real line break. That break may then be kept, removed or turned into a space depending on the receiving field. Single-line inputs often behave differently from multiline ones. That behavior varies by application and was not tested for this review.

  • Double escaping: if a string already contains a literal backslash and n and is serialized again, the result decodes to visible \n text rather than a break.
  • JSON: the JSON specification requires control characters, including LF and CR, to be escaped inside strings. A raw line break inside a JSON string makes the document invalid.
  • Line-ending conversion: editors, version control settings such as Git's autocrlf, and file transfer tools can convert between LF and CRLF. Escape sequences are unaffected. A literal line break inside a multiline literal can change unless the language normalizes it, as Java text blocks, JavaScript template literals and Go raw strings do.
  • Invisible whitespace: trailing spaces inside a multiline literal are part of the value, are easy to miss in review, and may be silently removed by an editor set to strip trailing whitespace on save.
  • Search and editing: line-oriented search tools do not match a phrase across a literal line break, and a phrase written with \n in one file and with a real break in another will not match the same query.
JSON.stringify("a\nb")   ->  "a\nb"    line feed escaped once; decodes to a real break
JSON.stringify("a\\nb")  ->  "a\\nb"   literal backslash escaped; decodes to backslash-n, not a break

Accessibility

For end users, the rendered output is what matters. Structure is better expressed with real markup, such as paragraphs and lists, than with repeated line breaks used for spacing. For developers who read code with a screen reader, an escape sequence is read as separate characters, while a multiline literal is read line by line. Which is easier depends on the screen reader and its punctuation settings. No documentation or test for a specific assistive technology was supplied, so check with the tools you actually use.

When a plain-text equivalent is needed

When the text is meant for people rather than code, such as documentation, support replies or copy review, share the rendered text with real line breaks, not the source literal. When sharing code, put the literal unchanged inside a code block so the destination does not interpret or reformat its escapes.

Evidence and gaps

The behaviors described here come from general language and data-format rules. No tool-specific evidence, measurements or destination tests were supplied. Copy-and-paste results in particular chat apps, editors, form fields and screen readers are unverified. To confirm what a string actually contains in your workflow, inspect its code points instead of relying on how it looks.

s = "line one\r\nline two"
print(repr(s))                   # shows the escapes explicitly
print([hex(ord(c)) for c in s])  # lists each code point, e.g. 0xd, 0xa