Python - Line Break in String
Line Break helps in making the string easier to read or display in a specific format. When working with lists, the join() method is useful, and formatted strings give us more control over our output.
Using \n for new line
The simplest way to add a line break in a string is by using the special character( \n). This character tells Python to break the string at that point and start a new line.
a = "Hello\nWorld"
print(a)
Output
Hello World
Let's look into other methods that use to break line in Python.
Table of Content
Using Triple Quotes for Multiline Strings
Another easy method to create multiline strings is by using triple quotes. This allows us to write the string across multiple lines directly.
b = """Hello
World"""
print(b)
Output
Hello World
Using String Join with a List
Sometimes we have a list of strings and want to join them with a line break in between. We can do this using the join() method.
c = ["Hello", "World"]
d = "\n".join(c)
print(d)
Output
Hello World
Using Format Strings
If we need more control over how the line breaks appear, we can use formatted strings with f-strings.
e = "Hello"
f = "World"
g = f"{e}\n{f}"
print(g)
Output
Hello World