本文目录导读:

我来系统地介绍Python字符串的基础操作,从定义到常用方法。
字符串的定义和创建
# 多种引号定义字符串 str1 = 'Hello World' str2 = "Python编程" str3 = '''多行 字符串''' str4 = """也是 多行字符串""" # 空字符串 empty_str = "" empty_str2 = str()
字符串基本操作
索引和切片
text = "Hello Python" # 索引(从0开始) print(text[0]) # H print(text[-1]) # n(最后一个字符) # 切片 [start:end:step] print(text[0:5]) # Hello print(text[6:]) # Python print(text[::-1]) # nohtyP olleH(反转)
字符串拼接
# 使用 + 号
first = "Hello"
second = "World"
result = first + " " + second # Hello World
# 使用 join() 方法
words = ["Python", "is", "fun"]
sentence = " ".join(words) # Python is fun
# 使用 f-string(推荐)
name = "小明"
age = 18
info = f"我叫{name},今年{age}岁" # 我叫小明,今年18岁
常用方法
大小写转换
text = "Hello Python" print(text.upper()) # HELLO PYTHON print(text.lower()) # hello python print(text.title()) # Hello Python(首字母大写) print(text.capitalize()) # Hello python
查找和替换
text = "Python is great, Python is powerful"
# 查找
print(text.find("Python")) # 0(返回第一次出现的位置)
print(text.find("Java")) # -1(未找到)
print(text.count("Python")) # 2(统计出现次数)
# 替换
print(text.replace("Python", "Java")) # 所有"Python"替换为"Java"
print(text.replace("Python", "Java", 1)) # 只替换第一个
判断方法
# 判断字符串类型
print("123".isdigit()) # True(是否全是数字)
print("abc".isalpha()) # True(是否全是字母)
print("abc123".isalnum()) # True(是否字母数字组合)
print(" ".isspace()) # True(是否全是空格)
# 判断开头结尾
print("hello.py".startswith("hello")) # True
print("hello.py".endswith(".py")) # True
实战示例
# 示例1:字符串清理
def clean_string(text):
"""清理字符串:去除空格和特殊字符"""
# 去除首尾空格
text = text.strip()
# 将所有单词首字母大写
text = text.title()
return text
# 示例2:密码验证
def check_password(password):
"""检查密码强度"""
if len(password) < 8:
return False, "密码长度至少8位"
if not any(c.isupper() for c in password):
return False, "需要包含大写字母"
if not any(c.isdigit() for c in password):
return False, "需要包含数字"
return True, "密码强度合格"
# 示例3:格式化输出
def format_user_info(name, age, city):
"""格式化用户信息"""
info = f"""
用户信息:
=========
姓名:{name}
年龄:{age}岁
城市:{city}
=========
"""
return info.strip()
练习题
# 练习1:提取邮箱用户名
email = "user@example.com"
username = email.split("@")[0]
print(f"用户名:{username}")
# 练习2:反转句子中的单词
sentence = "Hello World Python"
reversed_words = " ".join(sentence.split()[::-1])
print(reversed_words) # "Python World Hello"
# 练习3:统计词频
text = "the cat and the dog and the bird"
word_list = text.split()
word_count = {}
for word in word_list:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # {'the': 3, 'cat': 1, ...}
这些基础操作覆盖了Python字符串最常用的功能,建议你动手练习,逐个尝试每个方法,理解它们的使用场景。