12.字符串操作

12.字符串操作

欢迎来到《10天学会Python》第6天!今天学习字符串——Python中处理文本的神奇工具,像是现实中的“橡皮章”,印出我们想表达的文字。

核心概念

字符串是由字符组成的序列,用来表示文本信息。从简单的问候语到复杂的文章,字符串无处不在。

python

# 创建字符串示例
greeting = "你好,Python!"
name = '小明'
multiline = """这是一个
多行字符串"""

重要特性

  • 不可变性:创建后不能修改(像刻好的印章)
  • 有序性:字符有固定位置,索引从0开始
  • 支持索引切片:可获取任意部分字符
  • 丰富的操作方法:大小写转换、分割、替换等

理解不可变性

字符串的不可变性就像刻好的印章——可以盖印但不能修改字。Python中创建新字符串需要重新“刻章”。

python

text = "Hello"
new_text = text + " World"  # 创建新字符串"Hello World"
print(text)  # "Hello" 原字符串不变

创建字符串的三种方法

1. 使用单引号或双引号(最常用)

python

message1 = "今天是晴天"
message2 = '温度25度'

2. 使用三引号(适合多行文本)

python

poem = """春眠不觉晓,
处处闻啼鸟。
夜来风雨声,
花落知多少。"""

3. 使用str()函数转换

python

number = 100
text_number = str(number)  # "100"

字符串索引与切片

索引访问

字符串的每个字符都有位置编号(索引),从0开始:

python

word = "Python"
first_char = word[0]     # "P"
third_char = word[2]     # "t"
last_char = word[-1]     # "n"(负数从末尾开始)

切片操作

切片就像切蛋糕,可以获取字符串的一部分:

python

text = "Hello, World!"
slice1 = text[0:5]      # "Hello"(0到4位置)
slice2 = text[7:12]     # "World"(7到11位置)
slice3 = text[:5]       # "Hello"(从头到4位置)
slice4 = text[7:]       # "World!"(7位置到末尾)
slice5 = text[::2]      # "Hlo ol!"(每隔一个字符)

常用字符串方法

1. 大小写转换

python

text = "Hello Python"
upper_text = text.upper()   # "HELLO PYTHON"
lower_text = text.lower()   # "hello python"
title_text = text.title()   # "Hello Python"

2. 分割与连接

python

sentence = "苹果,香蕉,橙子,葡萄"
fruits = sentence.split(",")  # ["苹果", "香蕉", "橙子", "葡萄"]
new_sentence = "-".join(fruits)  # "苹果-香蕉-橙子-葡萄"

3. 查找与替换

python

text = "我喜欢苹果,也喜欢香蕉"
pos = text.find("苹果")    # 3(位置索引)
has_banana = "香蕉" in text  # True
new_text = text.replace("苹果", "橙子")  # "我喜欢橙子,也喜欢香蕉"

4. 去除空白字符

python

user_input = "   Python编程   "
clean_text = user_input.strip()    # "Python编程"
left_clean = user_input.lstrip()   # "Python编程   "
right_clean = user_input.rstrip()  # "   Python编程"

5. 判断方法

python

text1 = "Python123"
text2 = "python"
text3 = "12345"
print(text1.isalnum())  # True(字母或数字)
print(text2.isalpha())  # True(全是字母)
print(text3.isdigit())  # True(全是数字)
print(text2.startswith("py"))  # True

字符串格式化

1. f-string(Python 3.6+推荐)

python

name = "小明"
age = 18
score = 95.5
message = f"{name}今年{age}岁,考试得了{score}分"
# "小明今年18岁,考试得了95.5分"

2. format()方法

python

template = "{}买了{}斤{},花了{}元"
result = template.format("妈妈", 2, "苹果", 15.8)
# "妈妈买了2斤苹果,花了15.8元"

3. 格式化占位符

python

price = 9.99
quantity = 3
total = price * quantity
print("单价:%.2f元,数量:%d个,总计:%.2f元" % (price, quantity, total))
# "单价:9.99元,数量:3个,总计:29.97元"

实践应用示例

示例1:用户信息整理

python

# 整理用户输入的信息
user_input = "  张三,25岁,程序员  "
name = user_input.strip().split(",")[0]
print(f"用户姓名:{name}")  # "用户姓名:张三"

示例2:密码强度检查

python

def check_password(password):
    if len(password) < 8:
        return "密码太短"
    elif password.isdigit():
        return "密码不能全是数字"
    elif password.isalpha():
        return "密码不能全是字母"
    else:
        return "密码强度合格"

print(check_password("abc123"))  # "密码强度合格"

示例3:生成商品标签

python

product = "有机苹果"
price = 12.5
weight = 1.5
total = price * weight

label = f"""
===============
商品:{product}
单价:{price:.2f}元/斤
重量:{weight}斤
总计:{total:.2f}元
===============
"""
print(label)

示例4:统计文章字数

python

article = """Python是一种广泛使用的高级编程语言。
它设计清晰,语法简洁,适合初学者学习。"""

# 统计字数
char_count = len(article)
word_count = len(article.split())
line_count = len(article.split("\n"))

print(f"字符数:{char_count},词数:{word_count},行数:{line_count}")

示例5:手机号脱敏处理

python

def mask_phone(phone):
    if len(phone) == 11 and phone.isdigit():
        return phone[:3] + " ****" + phone[7:]
    else:
        return "无效手机号"

print(mask_phone("13800138000"))  # "138****8000"

练习题

第1组:基础操作

  1. text = "Python编程很有趣"完成以下操作:
    • 转换为大写
    • 获取前6个字符
    • 判断是否包含"编程"
  2. 将用户输入句子的每个单词首字母大写,其他字母小写。

第2组:应用实践

  1. 编写邮箱验证程序,要求:
    • 包含"@"和"."
    • 长度5-50字符
    • 返回True/False
  2. 统计文本中每个字符出现次数,如 text = "hello world"输出 h:1, e:1, l:3, o:2, w:1, r:1, d:1

第3组:综合应用

  1. 实现文本加密程序,规则:
    • 字符ASCII码加3
    • 数字转字母(0->a, ..., 9->j)
    • 空格不变
    • 编写加密和解密函数
  2. 开发购物小票生成器,根据输入的:
    • 商品名称、价格、数量列表生成格式整齐的小票,含明细、单价、数量、小计和总金额。

掌握字符串操作后,你就能处理各种文本任务了。继续加油,明天学习函数的定义与调用!

11.字典(Dict)操作 2026-01-21
13.函数的定义与调用 2026-01-21

评论区