Fundamentals 4 min read

Python String Basics: Common Techniques and Examples

This note explains how to declare Python strings with various quotes, embed quotes inside strings, use escape sequences, and apply raw strings and f‑strings, providing clear code snippets and their outputs for each case.

Lisa Notes
Lisa Notes
Lisa Notes
Python String Basics: Common Techniques and Examples

1. String declaration : A string can be defined using single quotes ('...'), double quotes ("..."), triple single quotes ('''...''' ), or triple double quotes ("""..."""). Example code shows variables a, b, c, d and prints them, producing hello world 床前明月光 疑是地上霜.

2. Embedding quotes : When the outer delimiters are single quotes, inner quotes must be double, and vice versa. Example n = "i say:'my name is jack'" and m = 'i say:"my name is nini"' print i say:'my name is jack' and i say:"my name is nini" respectively.

3. Escape characters : The backslash removes the special meaning of the following character. \' escapes a single quote, \" escapes a double quote, \n creates a newline, and \t creates a tab. Examples include e = "你\"好吗?", f = "欢迎学习\n Python", g = "今天天气\t很晴朗!", whose printed outputs are 欢迎学习, Python, and 今天天气 很晴朗 respectively.

4. Raw strings and formatted strings : Prefixing a string with r creates a raw string where backslashes are treated literally, e.g., h = r"i am a \teacher" prints i am a \teacher. Prefixing with f enables expression interpolation using {}. Example name = "张三", age = "22", print(f"我的姓名是:{name},年龄是:{age}") outputs 我的姓名是:张三,年龄是:22.

Pythonstringprogramming basicsEscape CharactersRaw StringFormatted String
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

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.