什么是 Python 字符串?
在 Python 中,字符串(str)是不可变的字符序列,用于表示文本数据。所有字符串方法都不会修改原字符串,而是返回一个新字符串。
常用字符串方法
s.upper():转换为大写s.lower():转换为小写s.strip():去除首尾空白字符s.replace(old, new):替换子串s.split(sep):按分隔符拆分为列表s.join(iterable):用字符串连接可迭代对象s.find(sub):查找子串位置(未找到返回 -1)s.startswith(prefix)/s.endswith(suffix):判断开头/结尾
格式化字符串
Python 提供多种字符串格式化方式:
# f-string(推荐,Python 3.6+)
name = "Alice"
age = 30
print(f"Hello, {name}. You are {age} years old.")
# .format()
print("Hello, {}. You are {} years old.".format(name, age))
# % 格式化(旧式)
print("Hello, %s. You are %d years old." % (name, age))
实用示例
# 示例:清洗和处理用户输入
user_input = " Hello, WORLD! "
cleaned = user_input.strip().lower().replace(" ", "_")
print(cleaned) # 输出: hello,_world!
# 示例:提取文件扩展名
filename = "document.pdf"
if filename.endswith(".pdf"):
print("这是 PDF 文件")
注意事项
- 字符串是不可变对象,所有“修改”操作都返回新字符串。
- 使用
in关键字检查子串更高效且可读性高:"cat" in "concatenate"→True。 - 对于大量字符串拼接,建议使用
''.join(list)而非+,以提高性能。