09 - 字符串str:文本处理

2 阅读2分钟

想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:github.com/tingaicompa… 仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。

09 - 字符串str:文本处理

学习目标: 掌握字符串操作方法


💻 代码示例

1. 字符串基础

s = "Hello, World!"

# 长度
print(len(s))  # 13

# 访问字符
print(s[0])   # H
print(s[-1])  # !

# 切片
print(s[0:5])   # Hello
print(s[7:])    # World!
print(s[::-1])  # !dlroW ,olleH (反转)

# 字符串是不可变的
# s[0] = 'h'  # ❌ 报错

2. 字符串方法

s = "hello world"

# 大小写
print(s.upper())       # HELLO WORLD
print(s.lower())       # hello world
print(s.capitalize())  # Hello world
print(s.title())       # Hello World

# 查找
print(s.find("world"))  # 6 (找不到返回-1)
print(s.index("world")) # 6 (找不到报错)
print(s.count("l"))     # 3

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

# 分割
words = s.split()  # 默认按空格分割
print(words)  # ['hello', 'world']

csv = "a,b,c"
parts = csv.split(",")
print(parts)  # ['a', 'b', 'c']

# 连接
words = ["hello", "world"]
print(" ".join(words))  # hello world
print("-".join(words))  # hello-world

# 去除空白
s = "  hello  "
print(s.strip())   # "hello"
print(s.lstrip())  # "hello  "
print(s.rstrip())  # "  hello"

# 判断
print("hello".startswith("he"))  # True
print("hello".endswith("lo"))    # True
print("123".isdigit())           # True
print("abc".isalpha())           # True

3. 字符串格式化

name = "Alice"
age = 20

# f-string(Python 3.6+,推荐)
print(f"我是{name},今年{age}岁")

# format方法
print("我是{},今年{}岁".format(name, age))
print("我是{n},今年{a}岁".format(n=name, a=age))

# %格式化(旧式)
print("我是%s,今年%d岁" % (name, age))

🎯 在算法题中的应用

# 第2课:字母异位词分组
def groupAnagrams(strs):
    groups = {}
    for word in strs:
        key = "".join(sorted(word))  # 字符串排序
        groups[key] = groups.get(key, []) + [word]
    return list(groups.values())

# 第18课:最长回文子串
def longestPalindrome(s):
    def expand(left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return s[left+1:right]

    result = ""
    for i in range(len(s)):
        # 奇数长度回文
        odd = expand(i, i)
        # 偶数长度回文
        even = expand(i, i+1)
        result = max(result, odd, even, key=len)
    return result

# 反转字符串
s = "hello"
reversed_s = s[::-1]  # olleh

🎓 小结

✅ 字符串是不可变的 ✅ 切片s[start:end], s[::-1]反转 ✅ 常用方法:split, join, strip, replace ✅ 判断:startswith, endswith, isdigit ✅ f-string格式化

下一步: 10-元组tuple.md


如果这篇内容对你有帮助,推荐收藏 AI Compass:github.com/tingaicompa… 更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。