New line character in python
In Python, the new line character is represented by the escape sequence \n
. This is used to indicate the end of a line in a string.
Here are a few ways to use the new line character in Python:
- String literal: You can use the
\n
escape sequence directly in a string literal:my_string = "Hello\nWorld" print(my_string) # Output: Hello # World
- Raw string: If you want to include a literal backslash (
\
) in your string, you can use a raw string by prefixing the string withr
. In this case, the\n
escape sequence will be treated as a literal backslash andn
:my_string = r"Hello\ World" print(my_string) # Output: Hello\ World
- String formatting: You can also use the new line character in string formatting using the
print()
function:my_string = "Hello" print(my_string + "\nWorld") # Output: Hello # World
- Multiline strings: Python also supports multiline strings using triple quotes (
"""
) or triple single quotes ('''
). In this case, you can use the new line character to separate lines:my_string = """Hello World""" print(my_string) # Output: Hello # World
Note that in Python 2.x, the new line character is represented by
\r\n
on Windows and\n
on Unix-like systems. However, in Python 3.x, the new line character is always represented by\n
, regardless of the operating system.