Python New Line: How to Use \n in Strings (With Examples)

In Python, a new line is the \n character. Put it anywhere inside a string and everything after it starts on the next line when you print it:

print("Hello\nWorld")
# Hello
# World

Below I cover the /n mix-up, a Windows path that breaks by itself, joining lists, triple quotes and writing files. The screenshots are real runs on Python 3.14.7.

Diagram showing the Python newline character as a single character and the bytes text mode writes on Windows
\n is one character in the string, but Windows text mode writes it as two bytes.

What the newline character \n is in Python

Here’s what’s actually inside a string that contains \n:

message = "Hello\nWorld"
print(message)
print()

print('len("\\n")   ->', len("\n"))
print('ord("\\n")   ->', ord("\n"))
print("stored as   ->", repr(message))
print()

print("the same character, written other ways:")
print('  chr(10) == "\\n"          ->', chr(10) == "\n")
print('  "\\x0a" == "\\n"           ->', "\x0a" == "\n")
print('  "\\N{LINE FEED}" == "\\n"  ->', "\N{LINE FEED}" == "\n")

Output:

Hello
World

len("\n")   -> 1
ord("\n")   -> 10
stored as   -> 'Hello\nWorld'

the same character, written other ways:
  chr(10) == "\n"          -> True
  "\x0a" == "\n"           -> True
  "\N{LINE FEED}" == "\n"  -> True
Command Prompt showing a Python string with a newline character printed on two lines and its length of one
\n prints as a line break, but it’s stored as a single character with code 10.

The backslash and the n are just how you type it. Python turns them into one character, the line feed, which is character code 10.

That’s why len("\n") is 1. When you want to see the newlines instead of their effect, print repr() of the string and they show up as \n again.

chr(10), \x0a and \N{LINE FEED} are the same character written other ways. You’ll rarely need them, but you’ll meet them in other people’s code.

Don’t confuse it with \r, the carriage return, which is code 13. Windows ends lines in files with \r\n, and that pair turns up again in the file and split sections below.

Is it \n or /n in Python?

It’s \n, with a backslash. A forward slash does nothing special, which is easy to miss:

print("Hello/nWorld")      # forward slash: two ordinary characters
print("Hello\nWorld")      # backslash: a real new line
print("Hello\\nWorld")     # doubled backslash: a literal \n
print(r"Hello\nWorld")     # raw string: also a literal \n
print()

print('len("/n")  ->', len("/n"))
print('len("\\n")  ->', len("\n"))
print('len(r"\\n") ->', len(r"\n"))

Output:

Hello/nWorld
Hello
World
Hello\nWorld
Hello\nWorld

len("/n")  -> 2
len("\n")  -> 1
len(r"\n") -> 2
Command Prompt comparing Python backslash n newline with forward slash n and a raw string
/n prints as two plain characters. Only the backslash version starts a new line.

"Hello/nWorld" prints exactly as typed, because / is an ordinary character. No error, no warning, just the wrong output.

I see this mostly from people who type URLs and web paths all day, where the forward slash is the habit. If your line break isn’t appearing, check the slash first.

Sometimes you want the opposite: a literal backslash and n, say for a regex or a help message. Double the backslash (\\n) or use a raw string (r"\n"). Both give you two characters.

\n is one of several escape sequences; the full set of Python escape sequences covers tabs, quotes and the rest.

Why a Windows file path breaks onto a new line

This one catches people constantly. The path below looks fine, but it’s hiding two escape sequences:

path = "C:\reports\new_sales.csv"

print("what Python stored:", repr(path))
print("contains a new line?      ", "\n" in path)
print("contains a carriage return?", "\r" in path)
print("split on new lines:", path.split("\n"))
print()

fixed = r"C:\reports\new_sales.csv"
print("raw string:", fixed)
print("contains a new line?      ", "\n" in fixed)
print("forward slashes work too: ", "C:/reports/new_sales.csv")

Output:

what Python stored: 'C:\reports\new_sales.csv'
contains a new line?       True
contains a carriage return? True
split on new lines: ['C:\reports', 'ew_sales.csv']

raw string: C:\reports\new_sales.csv
contains a new line?       False
forward slashes work too:  C:/reports/new_sales.csv
Command Prompt showing a Python Windows file path string that silently contains a newline and a carriage return
\r and \n in the path became real control characters. The raw string keeps the backslashes.

\r in \reports became a carriage return and \n in \new_sales.csv became a new line. Python didn’t complain, because both are valid escapes.

Opening that path fails with a confusing error, or worse, it prints across two lines in a log. Put an r in front of the string, or use forward slashes, which Windows accepts too.

If you’re on a Mac or Linux, your own paths use forward slashes, so you won’t hit this there. You’ll still meet it the day you paste in a Windows path from a colleague or a config file.

Unknown escapes are at least noisy. "\d" raises SyntaxWarning: "\d" is an invalid escape sequence, and a future version will make it an error. Raw strings avoid both problems.

Add a new line to a string in Python

Strings don’t have an append method, so you build a new string instead:

line = "Order #1042 shipped"
before = id(line)
line += "\n"
print(repr(line))
print("same string object as before?", id(line) == before)
print()

name, total = "Ava", 42.5
receipt = f"Customer: {name}\nTotal: ${total:.2f}\nDate: 2026-09-29"
print(receipt)
print()

try:
    "Hello".append("\n")
except AttributeError as err:
    print("AttributeError:", err)

Output:

'Order #1042 shipped\n'
same string object as before? False

Customer: Ava
Total: $42.50
Date: 2026-09-29

AttributeError: 'str' object has no attribute 'append'

+= looks like it changes the string, but the id check shows you get a brand new object. Strings can’t be changed in place, so there’s no append(), and calling it raises AttributeError.

For anything with values in it, an f-string with \n between the parts reads best. It’s also how I’d build a small receipt or address block.

Gluing many pieces together is a different job. For that, see the ways to concatenate strings in Python.

Join a list of strings with newlines

When the lines are already in a list, "\n".join() is the tool:

items = ["apples", "bread", "milk"]
shopping = "\n".join(items)
print(shopping)
print(repr(shopping))
print()

numbers = [3, 14, 15]
try:
    "\n".join(numbers)
except TypeError as err:
    print("TypeError:", err)
print("\n".join(str(n) for n in numbers))
print()

print("an empty list gives an empty string:", repr("\n".join([])))
print("add the last newline yourself:", repr("\n".join(items) + "\n"))

Output:

apples
bread
milk
'apples\nbread\nmilk'

TypeError: sequence item 0: expected str instance, int found
3
14
15

an empty list gives an empty string: ''
add the last newline yourself: 'apples\nbread\nmilk\n'
Command Prompt showing Python join a list of strings with a newline and the TypeError for a list of integers
join() puts \n between items only, and it refuses anything that isn’t a string.

I use join() far more than += in a loop. It builds the result in one go, and it can’t leave a stray newline hanging off the end.

The separator goes between items, so there’s no newline after the last one. Add it yourself when you’re writing lines to a file and want the file to end cleanly.

join() only accepts strings. A list of numbers raises TypeError: sequence item 0: expected str instance, int found, so convert them on the way in with str(n) for n in numbers.

There’s more on this pattern in turning a list of strings into one string, including other separators.

Multiline strings and docstrings with triple quotes

Triple quotes let you type real line breaks instead of \n. Watch the first line, though:

address = """
Ava Johnson
1200 Market Street
San Francisco, CA
"""
print(repr(address))

address = """\
Ava Johnson
1200 Market Street
San Francisco, CA"""
print(repr(address))
print(address)
print()

def order_total(price, qty):
    """Return the order total.

        price and qty are plain numbers.
    """
    return price * qty

print(repr(order_total.__doc__))

Output:

'\nAva Johnson\n1200 Market Street\nSan Francisco, CA\n'
'Ava Johnson\n1200 Market Street\nSan Francisco, CA'
Ava Johnson
1200 Market Street
San Francisco, CA

'Return the order total.\n\nprice and qty are plain numbers.\n'

A newline right after the opening quotes is part of the string, so the first version starts with \n. A backslash straight after the quotes swallows it.

Docstrings are triple-quoted strings too. Since Python 3.13, the compiler strips their common indentation, which is why __doc__ above has no leading spaces. I checked: 3.12 keeps them.

Ordinary triple-quoted strings inside a function still keep their indentation. textwrap.dedent() removes it.

Line breaks in your code versus in the string

Splitting a long line of code isn’t the same thing. Adjacent strings inside parentheses join with no newline at all. C