How to use escape characters in Python?

In Python, escape characters are represented by a backslash (\). Here are some common escape characters and their uses: 1. \n: newline character, used to create a new line in a string. 2. \t: tab character, used to create a horizontal tab in a string. 3. \’: single quote, used to insert a single quote in a string. 4. \”: double quote, used to insert a double quote in a string. 5. \\\: backslash, used to insert a backslash in a string. 6. \r: carriage return, used to move the cursor to the beginning of the current line. 7. \b: backspace character, used to move the cursor back one position. Here are some examples:

# 换行符

print("Hello\nWorld")

# 输出:

# Hello

# World

# 制表符

print("Hello\tWorld")

# 输出:

# Hello    World

# 插入单引号

print('I\'m a student')

# 输出:

# I'm a student

# 插入双引号

print("He said, \"Hello!\"")

# 输出:

# He said, "Hello!"

# 插入反斜杠

print("C:\\Users\\Username")

# 输出:

# C:\Users\Username

# 回车符

print("Hello\rWorld")

# 输出:

# World

# 退格符

print("Hello\bWorld")

# 输出:

# HellWorld

It’s important to note that if a string starts with r or R, the backslash will be treated as a regular character, not an escape character. For example:

print(r"C:\Users\Username")

# 输出:

# C:\Users\Username

This will print the original string without interpreting escape characters.

广告
Closing in 10 seconds
bannerAds