Python 字符串完全指南 🐍
📌 字符串的定义
在 Python 中,字符串(String)是由字符组成的不可变序列,用于表示文本数据。字符串可以使用单引号、双引号或三引号来定义:
# 单引号
str1 = 'Hello Python'
# 双引号
str2 = "Hello Python"
# 三引号(支持多行)
str3 = '''这是一个
多行字符串'''
str4 = """这也是一个
多行字符串"""
关键特性: 字符串是不可变的(immutable),一旦创建就不能修改其内容。
🔗 字符串拼接
Python 中的字符串拼接
str1 = "Hello"
str2 = "Python"
# 使用 + 运算符
result = str1 + " " + str2 # "Hello Python"
# 使用 * 运算符重复
repeat = "Hi" * 3 # "HiHiHi"
⚠️ 重要区别:Python vs JavaScript
Python 的字符串拼接不会影响原数据:
# Python示例
name = "张三"
greeting = "你好," + name
print(name) # 输出: 张三(原数据未改变)
print(greeting) # 输出: 你好,张三
# 字符串是不可变的
original = "Hello"
modified = original + " World"
print(original) # 仍然是 "Hello"
JavaScript 对比:
在 JavaScript 中,字符串同样是不可变的,但需要注意的是:
// JavaScript示例
let name = '张三'
let greeting = '你好,' + name
console.log(name) // 输出: 张三
console.log(greeting) // 输出: 你好,张三
// JavaScript中字符串也是不可变的
let original = 'Hello'
let modified = original + ' World'
console.log(original) // 仍然是 "Hello"
核心相似点: Python 和 JavaScript 在字符串拼接方面行为一致,都不会改变原始字符串,因为两种语言中字符串都是不可变类型。
🔍 字符串的成员运算符
Python 中的成员运算符
Python 使用 in 和 not in 运算符来检查子字符串是否存在:
text = "Hello Python World"
# 使用 in
print("Python" in text) # True
print("Java" in text) # False
# 使用 not in
print("Java" not in text) # True
print("Python" not in text) # False
🆚 与 JavaScript 的 includes()对比
是的!Python 的 in 运算符类似于 JavaScript 的 includes() 方法:
# Python
text = "Hello World"
result = "World" in text # True
// JavaScript
let text = 'Hello World'
let result = text.includes('World') // true
主要区别:
- Python: 使用
in运算符(更简洁) - JavaScript: 使用
includes()方法
✂️ 字符串切片
字符串切片是 Python 的强大特性,语法为 string[start:end:step]:
text = "Hello Python"
# 基本切片
print(text[0:5]) # "Hello"
print(text[6:]) # "Python"
print(text[:5]) # "Hello"
# 负索引
print(text[-6:]) # "Python"
print(text[:-7]) # "Hello"
# 步长
print(text[::2]) # "HloPto"(每隔一个字符)
print(text[::-1]) # "nohtyP olleH"(反转字符串)
# 实用示例
url = "https://www.python.org"
print(url[8:]) # "www.python.org"
print(url[8:-4]) # "www.python"
🛠️ 常用字符串方法
1️⃣ count() - 统计子串出现次数
text = "banana"
print(text.count("a")) # 3
print(text.count("an")) # 2
print(text.count("x")) # 0
# 可以指定范围
print(text.count("a", 0, 3)) # 1(在索引0到3之间)
2️⃣ isalnum() - 检查是否为字母数字
str1 = "abc123"
str2 = "abc 123"
str3 = "abc@123"
print(str1.isalnum()) # True(只包含字母和数字)
print(str2.isalnum()) # False(包含空格)
print(str3.isalnum()) # False(包含特殊字符)
3️⃣ isalpha() - 检查是否只包含字母
str1 = "Hello"
str2 = "Hello123"
str3 = "你好世界"
print(str1.isalpha()) # True
print(str2.isalpha()) # False(包含数字)
print(str3.isalpha()) # True(中文字符也算字母)
4️⃣ join() - 连接字符串序列
# 用指定分隔符连接列表
words = ["Python", "is", "awesome"]
print(" ".join(words)) # "Python is awesome"
print("-".join(words)) # "Python-is-awesome"
# 连接字符
chars = ["a", "b", "c"]
print("".join(chars)) # "abc"
print(", ".join(chars)) # "a, b, c"
# 实用场景:构建路径
path_parts = ["home", "user", "documents"]
print("/".join(path_parts)) # "home/user/documents"
5️⃣ split() - 分割字符串
text = "Python is awesome"
# 默认按空格分割
print(text.split()) # ['Python', 'is', 'awesome']
# 指定分隔符
csv = "apple,banana,orange"
print(csv.split(",")) # ['apple', 'banana', 'orange']
# 限制分割次数
print(text.split(" ", 1)) # ['Python', 'is awesome']
# 处理多个空格
text2 = "Python is awesome"
print(text2.split()) # ['Python', 'is', 'awesome'](自动处理多余空格)
6️⃣ startswith() - 检查开头
url = "https://www.python.org"
filename = "report.pdf"
print(url.startswith("https")) # True
print(url.startswith("http")) # True
print(url.startswith("ftp")) # False
print(filename.startswith("report")) # True
print(filename.endswith(".pdf")) # True(endswith是类似方法)
# 可以检查多个前缀
print(url.startswith(("http", "https", "ftp"))) # True
🎯 综合示例
# 实际应用示例
def process_text(text):
"""处理文本的综合示例"""
# 清理和分割
words = text.strip().split()
# 统计信息
word_count = len(words)
char_count = len(text.replace(" ", ""))
# 过滤出字母单词
alpha_words = [w for w in words if w.isalpha()]
# 连接处理后的单词
processed = " ".join(alpha_words)
return {
"original": text,
"word_count": word_count,
"char_count": char_count,
"alpha_words": alpha_words,
"processed": processed
}
# 测试
result = process_text("Hello Python 2024! Learn coding.")
print(result)
输出:
{
'original': 'Hello Python 2024! Learn coding.',
'word_count': 5,
'char_count': 28,
'alpha_words': ['Hello', 'Python', 'Learn', 'coding'],
'processed': 'Hello Python Learn coding'
}
📚 更多常用字符串方法速查
| 方法 | 功能 | 示例 |
|---|---|---|
upper() | 转大写 | "hello".upper() → "HELLO" |
lower() | 转小写 | "HELLO".lower() → "hello" |
strip() | 去除首尾空白 | " hi ".strip() → "hi" |
replace() | 替换子串 | "hi".replace("i", "o") → "ho" |
find() | 查找子串位置 | "hello".find("ll") → 2 |
format() | 格式化字符串 | "Hi {}".format("Tom") → "Hi Tom" |
capitalize() | 首字母大写 | "hello".capitalize() → "Hello" |
title() | 每个单词首字母大写 | "hello world".title() → "Hello World" |
💡 小贴士
- 字符串不可变性:任何看似"修改"字符串的操作都会创建新字符串
- 性能考虑:大量拼接时使用
join()比+更高效 - f-string:Python 3.6+推荐使用 f-string 进行格式化:
name = "Python" version = 3.11 print(f"{name} {version}") # "Python 3.11" - 链式调用:可以连续调用多个方法:
text = " hello world " result = text.strip().upper().replace(" ", "-") print(result) # "HELLO-WORLD"
🎉 掌握这些字符串操作,你的 Python 技能将更上一层楼!
#Python #编程 #字符串操作 #学习笔记