# === 字符串高级操作 ===
# 1. 字符串切片:取一部分
msg = "Hello,Python!"
print(msg[0]) # 第1个字符:H
print(msg[6]) # 第7个字符:P
print(msg[0:5]) # 索引0到4:Hello
print(msg[7:13]) # 索引7到12:Python
print(msg[:5]) # 从头到索引4:Hello
print(msg[7:]) # 从索引7到末尾:Python!
print(msg[-1]) # 最后一个:!
print(msg[-6:]) # 后6个:thon!
print()
# 2. 字符串查找
email = "firebird@example.com"
print(email.find("@")) # 返回位置索引:8
print(email.find("abc")) # 找不到返回:-1
print("example" in email) # 是否包含:True
print()
# 3. 字符串替换
text = "我喜欢Java"
new_text = text.replace("Java", "Python")
print(text) # 原字符串不变:我喜欢Java
print(new_text) # 替换后:我喜欢Python
print()
# 4. 字符串分割与拼接
sentence = "苹果,香蕉,橘子,葡萄"
fruits = sentence.split(",") # 按逗号分割成列表
print(fruits) # ['苹果', '香蕉', '橘子', '葡萄']
joined = " | ".join(fruits) # 用 | 拼接成字符串
print(joined) # 苹果 | 香蕉 | 橘子 | 葡萄
print()
# 5. 去除首尾空白
name = " 火鸟 "
print(f"[{name}]") # [ 火鸟 ]
print(f"[{name.strip()}]") # [火鸟]
print(f"[{name.lstrip()}]") # [火鸟 ] 去左边
print(f"[{name.rstrip()}]") # [ 火鸟] 去右边
print()
# 6. 大小写转换
word = "Hello World"
print(word.upper()) # HELLO WORLD
print(word.lower()) # hello world
print(word.title()) # Hello World(每个单词首字母大写)
print()
# 7. 判断字符串类型
print("123".isdigit()) # 是否全是数字:True
print("abc".isalpha()) # 是否全是字母:True
print("abc123".isalnum()) # 是否字母或数字:True
print(" ".isspace()) # 是否全是空白:True
print()
# 8. 实战:文本处理小程序
text = " Python is the BEST language。I love python! "
print(f"原文: [{text}]")
# 清理:去首尾空格 + 统一小写 + 替换中文标点
clean = text.strip().lower().replace("。", ".").replace("!", "!")
print(f"清理后: [{clean}]")
# 统计单词数
words = clean.split()
print(f"单词数: {len(words)}")
print(f"单词列表: {words}")
# 查找是否包含python
if "python" in clean:
print("找到了 python!")
# 替换
happy = clean.replace("best", "amazing")
print(f"替换后: {happy}")
必须熟练的:
| 操作 | 示例 |
|---|---|
| 切片取子串 | msg[0:5]、msg[7:]、msg[-3:] |
| 分割字符串 | sentence.split(",") |
| 拼接列表 | ",".join(fruits) |
| 去空白 | text.strip() |
| 统一大小写 | text.lower() |
了解即可的:
| 操作 | 示例 |
|---|---|
| 查找位置 | email.find("@") |
| 替换 | text.replace("a", "b") |
| 大小写转换 | upper()、title() |
| 判断类型 | isdigit()、isalpha() |
未经允许不得转载:百花谷博客 » 跟着AI学Python 第6课:字符串高级操作

百花谷博客
微信关注,获取更多