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.
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.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
