Skip to content

Python 字符串

Master Python 字符串: slicing, 方法, f-字符串, 格式化, and encoding for 文本处理.

你将学到

  • 创建 and slice 字符串使用 indexing
  • Use 必要字符串方法 (拆分, 连接, replace, strip)
  • 格式字符串使用 f-字符串 and 格式()
  • 检查 and 搜索字符串使用 in, startswith, 查找
  • Handle multi-行 and raw 字符串

概念讲解

Creating Strings

Strings in Python are immutable sequences of Unicode characters. You create them with single, double, or triple quotes:

single = 'hello'
double = "世界"
multi = """This is a
multi-line string"""
raw = r"C:\path\否\escape"

Triple quotes are ideal for docstrings and multi-line text. Raw strings (prefixed with r) treat backslashes literally — essential for Windows paths and regex patterns.

Indexing and Slicing

You access characters by index and extract substrings with slicing [开始:停止:步骤]:

text = "Python"
print(text[0])     # P  (first char)
print(text[-1])    # n  (last char)
print(text[0:3])   # Pyt (chars 0,1,2)
print(text[2:])    # thon (from index 2 to end)
print(text[::-1])  # nohtyP (reversed!)

Negative indices count from the end. The slice [::-1] is the idiomatic way to reverse a string. Slicing never raises an IndexError — it just returns what is available.

Essential String Methods

Python strings come with dozens of built-in methods. The most used ones:

  • .拆分() — break a string into a list of substrings
  • .连接() — combine a list of strings with a separator
  • .replace() — replace all occurrences of a substring
  • .strip() — remove leading/trailing whitespace
  • .upper() / .lower() — change case
  • .startswith() / .endswith() — check prefixes/suffixes
  • .查找() — return the index of a substring, or -1
csv_line = "Ada,25,admin"
parts = csv_line.split(",")        # ['Ada', '25', 'admin']
joined = "-".join(parts)           # Ada-25-admin
clean = " hello ".strip()        # hello

F-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are the fastest and most readable way to embed expressions in strings:

name = "Ada"
age = 25
print(f"{name} 是 {age} years 旧")
print(f"下一个 year: {age + 1}")
print(f"{name:>10}")    # right-align in 10 chars
print(f"{3.14159:.2f}") # 3.14 (2 decimal places)

F-strings support format specifiers for alignment, width, precision, and more. They are preferred over the older % formatting and .格式() method.

Searching and Checking

text = "Hello, Python!"
print("Python" in text)          # True
print(text.startswith("Hello"))  # True
print(text.find("Python"))       # 7 (index)
print(text.find("Java"))         # -1 (not found)

Use the in operator for membership tests — it is clearer than .查找() != -1. Because strings are immutable, every "modification" method returns a new string; the original is never changed in place.

示例代码

              # Creating strings
single = 'hello'
double = "world"
multi = """Multi-line
string here"""
raw = r"C:\users\ada"  # backslashes are literal

# Indexing and slicing
text = "Python"
print(text[0])      # P
print(text[-1])     # n
print(text[0:3])    # Pyt
print(text[::-1])   # nohtyP (reversed)

# Essential methods
csv_line = "Ada,25,admin"
parts = csv_line.split(",")
print(parts)                    # ['Ada', '25', 'admin']
print("-".join(parts))          # Ada-25-admin
print("  hello  ".strip())      # hello
print("hello".replace("l", "L"))  # heLLo

# F-strings
name = "Ada"
age = 25
print(f"{name} is {age} years old")
print(f"{3.14159:.2f}")         # 3.14
print(f"{name:>10}")            # right-aligned

# Searching
sentence = "Hello, Python!"
print("Python" in sentence)     # True
print(sentence.startswith("H")) # True
print(sentence.find("Java"))    # -1
            

Demonstrates 字符串 creation, slicing (包含 reverse), 键方法 (拆分, 连接, strip, replace), f-字符串格式化使用 specifiers, and membership 测试使用 in and 查找.

动手试一试

  • 文本计数器

    数量 characters, words, and 行 — classic 字符串操作.

  • 情况 Converter

    Convert 之间 snake_case, camelCase, etc. using 字符串方法.

常见错误

错误写法

Trying 到修改字符串 in 位置如 文本[0] = 'p'

正确做法

字符串是 不可变. Use 文本 = 文本.replace('P', 'p') or 文本 = 'p' + 文本[1:] 到创建新 字符串. 这个是 大多数常见初学者 surprise 使用字符串.

错误写法

Confusing 查找() returning -1 使用有效索引

正确做法

查找() 返回 -1 当 substring 是不 找到, 哪个是 有效索引从 端. Use 'in' 运算符 for membership 测试, or use .索引() 哪个 raises ValueError 如果不 找到.

相关速查表

练习 Python 字符串

18 个练习

练习 Python 字符串

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误