# GESP等级：三级 | GESP Python 三级考点

# 第9课·第3节 —— 字符串方法下：find/replace/count/len/startswith
# GESP 考点：#9 字符串（方法综合应用）
# 记忆钩子："find()找位置  replace()换内容  count()数次数"

# ============================================================
# 第一部分：find() —— 找位置
# ============================================================
print("=" * 40)
print("【1】find() —— 在字符串里找子串的位置")
print("=" * 40)

s = "hello"

# 基本用法：找单个字符
print("s =", repr(s))
print("s.find('e'):", s.find("e"))       # 1 → 'e'在第1位
print("s.find('l'):", s.find("l"))       # 2 → 第一个'l'在第2位
print("s.find('z'):", s.find("z"))       # -1 → 找不到返回-1

# 找子串（多个字符）
print("s.find('llo'):", s.find("llo"))   # 2 → 'llo'从第2位开始

# 重要：计算机从0开始数
print()
print("索引说明：")
print("  h   e   l   l   o")
print("  0   1   2   3   4")
print("      ↑ find('e') = 1")

# 练习：
# Q: "hello python".find("python") 是多少？
test_str = "hello python"
print()
print(f"'{test_str}'.find('python'):", test_str.find("python"))  # 6

print()

# ============================================================
# 第二部分：replace() —— 换内容
# ============================================================
print("=" * 40)
print("【2】replace() —— 把旧内容换成新内容")
print("=" * 40)

s = "hello"

# 全部替换
print("s =", repr(s))
print("s.replace('l', 'w'):", s.replace("l", "w"))       # hewwo

# 指定替换次数（只换前N个）
print("s.replace('l', 'w', 1):", s.replace("l", "w", 1)) # hewlo

# 重要：原字符串不变！
print()
print("⚠️  字符串不可变！")
print("替换后打印原字符串 s:", s)   # 还是 "hello"

# 要保存结果，必须赋给新变量
new_s = s.replace("l", "w")
print("保存到新变量 new_s:", new_s)  # "hewwo"

# 更多例子
print()
print("更多替换例子：")
hw = "hello world"
print(f"'{hw}'.replace(' ', ','):", hw.replace(" ", ","))  # hello,world

print("'hello world nice'.replace(' ', ',', 1):",
      "hello world nice".replace(" ", ",", 1))  # hello,world nice

print()

# ============================================================
# 第三部分：count() —— 数次数
# ============================================================
print("=" * 40)
print("【3】count() —— 统计子串出现的次数")
print("=" * 40)

s = "banana"
print("s =", repr(s))
print("s.count('a'):", s.count("a"))        # 3
print("s.count('na'):", s.count("na"))      # 2
print("s.count('z'):", s.count("z"))        # 0

print()
print("对比 find 和 count：")
print(f"  s.find('a')  → {s.find('a')}  (找位置)")
print(f"  s.count('a') → {s.count('a')} (数次数)")

print()

# ============================================================
# 第四部分：startswith() / endswith() —— 判断开头和结尾
# ============================================================
print("=" * 50)
print("【4】startswith() / endswith() —— 判断开头/结尾")
print("=" * 50)

s = "hello.py"
print("s =", repr(s))
print("s.startswith('he'):", s.startswith("he"))       # True
print("s.startswith('hel'):", s.startswith("hel"))      # True
print("s.startswith('Hello'):", s.startswith("Hello"))  # False → 大小写敏感
print("s.endswith('.py'):", s.endswith(".py"))          # True
print("s.endswith('.txt'):", s.endswith(".txt"))        # False

print()
print("实际应用：筛选文件")
files = ["cat.jpg", "dog.jpg", "notes.txt", "main.py", "photo.png"]
for f in files:
    if f.endswith(".jpg"):
        print(f"  {f} 是图片文件！")
    elif f.endswith(".py"):
        print(f"  {f} 是Python代码文件！")

print()

# ============================================================
# 第五部分：len() —— 求长度（函数，不是方法！）
# ============================================================
print("=" * 40)
print("【5】len() —— 求字符串长度（函数）")
print("=" * 40)

print("len('hello'):", len("hello"))            # 5
print("len('banana'):", len("banana"))          # 6
print("len('hello world'):", len("hello world"))# 11（空格也算）
print("len(''):", len(""))                      # 0

print()
print("⚠️  len 是函数，不是方法！")
print("   方法前面有点号：s.find()、s.replace()")
print("   函数前面没有点号：len(s)")

print()
print("对比 len 和 count：")
word = "banana"
print(f"  len('{word}')   → {len(word)}  (所有字符总数)")
print(f"  '{word}'.count('a') → {word.count('a')} (只数'a')")

print()

# ============================================================
# 第六部分：综合演示 —— turtle 颜色名实战
# ============================================================
print("=" * 60)
print("【6】综合演示：用字符串方法分析 turtle 颜色名")
print("=" * 60)

colors = ["red", "blue", "green", "yellow", "purple",
          "orange", "pink", "brown", "black", "white"]

# 演示1：用 find() 查找哪些颜色包含 'e'
print("\n--- 演示1：find() → 查找含 'e' 的颜色 ---")
for c in colors:
    pos = c.find("e")
    if pos != -1:
        print(f"  '{c}' 中包含 'e'，在第 {pos} 位")
    else:
        print(f"  '{c}' 中不包含 'e' (返回 {pos})")

# 演示2：用 replace() 给颜色改名
print("\n--- 演示2：replace() → 把 'e' 替换成 '3' ---")
for c in colors:
    new_name = c.replace("e", "3")
    print(f"  {c} → {new_name}")

# 演示3：用 count() 统计各颜色中 'e' 的出现次数
print("\n--- 演示3：count() → 统计各颜色中 'e' 的个数 ---")
for c in colors:
    e_count = c.count("e")
    print(f"  '{c}' 中有 {e_count} 个 'e'")

# 演示4：用 startswith() 找出以 'b' 开头的颜色
print("\n--- 演示4：startswith() → 找以 'b' 开头的颜色 ---")
for c in colors:
    if c.startswith("b"):
        print(f"  '{c}' 以 'b' 开头")

# 演示5：用 len() 统计颜色名长度
print("\n--- 演示5：len() → 统计颜色名长度 ---")
for c in colors:
    print(f"  '{c}' 的长度是 {len(c)}")

# 演示6：综合报告
print("\n" + "=" * 60)
print("★★★ 颜色分析综合报告 ★★★")
print("=" * 60)
print(f"{'颜色名':8} | {'长度':5} | {'含e位置':6} | {'a出现次数':7} | {'以b开头'}")
print("-" * 50)
for c in colors:
    length = len(c)
    e_pos = c.find("e")
    a_cnt = c.count("a")
    starts_b = c.startswith("b")
    e_str = str(e_pos) if e_pos != -1 else "无"
    print(f"{c:8} | {length:3}    | {e_str:>4}    | {a_cnt:4}       | {starts_b}")

print()

# ============================================================
# 第七部分：常用方法速查
# ============================================================
print("=" * 40)
print("【7】字符串方法速查表")
print("=" * 40)
print()
print("方法             作用                   示例                         结果")
print("-" * 75)
print("s.find(sub)     找子串位置              'hello'.find('e')            1")
print("s.replace(a,b)  替换内容                'hello'.replace('l','w')     hewwo")
print("s.count(sub)    统计次数                'banana'.count('a')          3")
print("s.startswith(x) 判断开头                'hello'.startswith('he')     True")
print("s.endswith(x)   判断结尾                'hello.py'.endswith('.py')   True")
print("len(s)          求长度(函数)            len('hello')                 5")
print()
print("记忆钩子：")
print("  find()找位置    replace()换内容    count()数次数")
print()
