Python: Quote String

By Xah Lee. Date: . Last updated: .

Summary

Quote String

Use single quote or double quote.

a = "this "
b = 'and that'
print(a, b)

String Escape

Use \n for linebreak, and \t for tab.

Raw string (No Backslash Escape)

Add r in front of the quote symbol. This way, backslash characters will be interpreted as is, not as escapes. (“r” for “raw”)

c = r"this \n and that"

print(c) # prints a single line

Quote Multi-Lines

To quote a string of multiple lines, use triple quotes.

d = """this
will be printed
in 3 lines"""

print(d)

# output:

# this
# will be printed
# in 3 lines

Python 2, String Containing Unicode

Python 2: If your string contain literal Unicode chars, such as α, then prefix your string with “u”, like this: u"greek α". But you also need to add a declaration #-*- coding: utf-8 -*-. The “r” and “u” can be combined, like this: ur"I ♥ Python" See: Python: Unicode Tutorial 🐍 .

Add u in front of the quote symbol if you string contains unicode characters. e.g. u"I ♥ U". It can be combined with r, e.g. ur"/I ♥ U/", and can also used in front of triple quote.

# -*- coding: utf-8 -*-
# python 2

# raw string
s1 = r"a\nb"

print(len(s1) == 4) # True
# -*- coding: utf-8 -*-
# python 2

s2 = ur"/I♥U/"

print len(s2) == 5 # True

Python String

Python

Overview

Help

String

Arithmetic

Boolean

Conditional

Loop, Iteration

Data Structure

Function and Class

Module

Misc

Regex

Text Processing

Web

Misc