全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 7 分钟 ✍️ juanwangdev

Python字符串基础操作

字符串是不可变序列,支持丰富的创建、拼接、切片和格式化操作。

字符串创建

单引号和双引号

Python
s1 = 'hello'
s2 = "hello"

# 包含引号
s3 = 'He said "hello"'
s4 = "It's a test"

三引号(多行字符串)

Python
s5 = '''line 1
line 2
line 3'''

s6 = "line 1
line 2
line 3"

print(s5)  # 保留换行格式

原始字符串(r-string)

Python
# 普通字符串:转义生效
s1 = "C:\\Users\\name"  # 需双反斜杠

# 原始字符串:转义不生效
s2 = r"C:\Users\name"   # 反斜杠原样保留

字符串拼接

加法拼接

Python
s1 = "hello"
s2 = "world"
result = s1 + " " + s2
print(result)  # hello world

join 方法(高效)

Python
words = ["hello", "world", "python"]
result = " ".join(words)
print(result)  # hello world python

# 不同分隔符
print("-".join(words))  # hello-world-python

重复拼接

Python
s = "ab"
print(s * 3)  # ababab

字符串切片

基本切片

Python
s = "hello world"

# 索引访问
print(s[0])    # h
print(s[-1])   # d

# 切片 [start:end:step]
print(s[0:5])   # hello
print(s[6:11])  # world
print(s[:5])    # hello(从头开始)
print(s[6:])    # world(到结尾)

步长切片

Python
s = "hello"

# 每隔一个字符
print(s[::2])   # hlo

# 反转字符串
print(s[::-1])  # olleh

字符串格式化

f-string(推荐)

Python
name = "Alice"
age = 25

# 基本用法
print(f"{name} is {age} years old")

# 表达式
print(f"{name.upper()}")

# 格式化数字
print(f"{age:03d}")      # 025(补零)
print(f"{3.14159:.2f}")  # 3.14(两位小数)

format 方法

Python
# 基本用法
print("{} is {} years old".format("Alice", 25))

# 位置参数
print("{0} is {1} years old, {0} lives in Beijing".format("Alice", 25))

# 关键字参数
print("{name} is {age} years old".format(name="Alice", age=25))

% 格式化(旧语法)

Python
name = "Alice"
age = 25

print("%s is %d years old" % (name, age))

常用方法

查找方法

Python
s = "hello world"

# 查找子串位置
print(s.find("world"))   # 6
print(s.find("python"))  # -1(未找到)

# 查找并报错
print(s.index("world"))   # 6
# s.index("python")  # ValueError

# 统计出现次数
print(s.count("o"))  # 2

替换方法

Python
s = "hello world"

# 替换
print(s.replace("world", "python"))  # hello python

# 替换次数限制
print(s.replace("o", "O", 1))  # hellO world

分割与连接

Python
s = "hello world python"

# 分割
print(s.split())      # ['hello', 'world', 'python']
print(s.split(" "))   # ['hello', 'world', 'python']

# 按换行分割
lines = "line1\nline2\nline3"
print(lines.splitlines())  # ['line1', 'line2', 'line3']

大小转换

Python
s = "Hello World"

print(s.upper())      # HELLO WORLD
print(s.lower())      # hello world
print(s.title())      # Hello World(标题化)
print(s.capitalize()) # Hello world(首字母大写)

去除空白

Python
s = "  hello  "

print(s.strip())   # hello(去除两端)
print(s.lstrip())  # hello  (去除左侧)
print(s.rstrip())  #   hello(去除右侧)

判断方法

Python
s = "hello"

print(s.startswith("he"))  # True
print(s.endswith("lo"))    # True
print(s.isalpha())         # True(全是字母)
print(s.isdigit())         # False(全是数字)
print(s.isalnum())         # True(字母或数字)
print(s.islower())         # True(全小写)

字符串不可变

不可直接修改

Python
s = "hello"
# s[0] = "H"  # TypeError

# 必须创建新字符串
s = "H" + s[1:]  # Hello

要点总结

  1. 字符串不可变,操作返回新字符串
  2. 三引号支持多行,原始字符串保留反斜杠
  3. f-string 是推荐格式化方式
  4. join() 比加法拼接高效
  5. 切片 [start:end:step] 灵活访问子串

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python基本数据类型
下一篇 → Python布尔类型与逻辑值
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库