Python 字符串操作详解
概述
字符串是编程中最常用的数据类型之一,特别是在文本处理、数据清洗和自然语言处理等领域。掌握字符串操作是 Python 编程的基础技能。
基础操作:索引与切片
理解索引和切片是操作字符串的第一步。Python 的索引从 0 开始,负数索引表示从末尾倒数。切片语法 [start:end:step] 非常灵活,甚至可以用来反转字符串。
text = "Hello, Python World!"
print(f"原始字符串:'{text}'")
# 索引
print(f"第一个字符:'{text[0]}'")
print(f"最后一个字符:'{text[-1]}'")
# 切片
print(f"前 5 个字符:'{text[:5]}'")
print(f"反转字符串:'{text[::-1]}'")
print(f"字符串长度:{len(text)}")
常用方法:清洗与转换
实际开发中,我们常需要对字符串进行清洗(去除空白)、大小写转换或查找替换。这些方法大多返回新字符串,不会修改原对象。
sample_text = " Hello, Python! Welcome to the World of Python Programming. "
stripped = sample_text.strip()
print(f"去除首尾空白:'{stripped}'")
# 大小写转换
print(f"全部大写:'{stripped.upper()}'")
print(f"首字母大写:'{stripped.capitalize()}'")
# 查找与替换
print(f"'Python'出现的次数:{stripped.count()}")
replaced = stripped.replace(, )
()
words = stripped.split()
joined = .join(words[:])
()


