Fundamentals 3 min read

Understanding Python String Prefixes: u, r, b, and f

Python string prefixes such as u (Unicode), r (raw), b (bytes), and f (formatted) indicate special string types, with each prefix altering how the string is interpreted, and the article explains their meanings, usage, and provides code examples for each.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python String Prefixes: u, r, b, and f

In Python, string prefixes are used to denote special string types, and this article explains the four common prefixes and their meanings.

u prefix (Unicode) : Indicates a Unicode string. In Python 3 all strings are Unicode by default, so the u prefix is rarely needed. Example: u"Hello World" .

r prefix (Raw) : Creates a raw string where backslashes are treated literally and escape sequences are not processed. Example: r"C:\Users\Username" .

b prefix (Bytes) : Denotes a bytes literal, used for binary data. Bytes strings are sequences of bytes and can contain any binary data. Example: b"Hello World" .

f prefix (Formatted) : Introduces an f‑string, allowing expressions and variables to be embedded directly within the string using curly braces. Example: name = "Alice"; f"Hello, {name}!" .

These prefixes are optional, but selecting the appropriate one can make string handling clearer and more convenient.

# Unicode字符串
name = u"李雷"
print(name)  # 输出:李雷
# 原始字符串
path = r"C:\Users\Username"
print(path)  # 输出:C:\Users\Username
# 字节字符串
data = b"\x48\x65\x6c\x6c\x6f"  # ASCII编码的"Hello"
print(data)  # 输出:b"Hello"
# 格式化字符串
age = 25
print(f"My age is {age}." )  # 输出:My age is 25.

The examples demonstrate how each prefix affects string interpretation: Unicode strings for text, raw strings to ignore escapes, bytes strings for binary data, and formatted strings for convenient interpolation.

UnicodebytesFormatted StringsRaw StringsString Prefixes
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.