Python 字符串基础:定义、索引、切片及常用方法详解
1. 字符串概述
字符串是 Python 中最常用的数据类型之一,用于表示文本信息。在 Python 中,字符串是不可变序列,一旦创建就不能修改其内容。我们可以使用单引号 、双引号 或三引号 / 来创建字符串。
本文详细介绍了 Python 字符串的基础知识,包括字符串的定义与创建方式、格式化输出与输入操作、索引与切片机制、以及查找、修改、大小写转换等常用方法。此外还涵盖了字符串运算符、不可变性原理及编码注意事项,帮助开发者掌握字符串处理的核心技能。

字符串是 Python 中最常用的数据类型之一,用于表示文本信息。在 Python 中,字符串是不可变序列,一旦创建就不能修改其内容。我们可以使用单引号 、双引号 或三引号 / 来创建字符串。
'"'''"""# 单引号
var1 = 'Hello World!'
# 双引号
var2 = "Python Runoob"
# 三引号(支持多行)
var3 = """hello world
i love you """
Python 支持多种字符串格式化方式,包括 % 操作符、format() 方法和 f-string。
name = "TOM"
age = 18
height = 180.5
# % 格式化
print("我的名字是%s"%name)
print("我今年%d岁了"%age)
print("我的身高是%.2f"%height)
# format() 方法
print("大家好,我叫{},我今年{}岁,我的身高是{}".format(name, age, height))
# f-string (Python 3.6+)
print(f"大家好,我叫{name},我今年{age}岁,我的身高是{height}")
使用 input() 函数获取用户输入,返回值默认为字符串类型。
name = input("请输入你的名字:")
print(type(name)) # <class 'str'>
字符串支持通过索引访问单个字符,索引从 0 开始,负数表示从末尾倒数。
var1 = "hello python"
print(var1[1]) # e
print(var1[-1]) # n
切片语法为 [start:end:step],包含起始位置,不包含结束位置。
name = "hellopython"
print(name[2:5]) # llo
print(name[:5]) # hello
print(name[1:]) # ellopython
print(name[::-1]) # nohtpyolleh (反转)
print(name[::2]) # hlopyn (步长为 2)
find(sub[, start[, end]]): 找到返回索引,未找到返回 -1。index(sub[, start[, end]]): 找到返回索引,未找到抛出异常。count(sub[, start[, end]]): 统计子串出现次数。rfind(), rindex(): 从右侧开始查找。var = "hello and python and hello world"
print(var.find("and")) # 6
print(var.index("ors")) # ValueError
print(var.count("and")) # 2
字符串是不可变的,修改操作会返回新字符串。
replace(old, new[, count]): 替换子串。split(sep[, maxsplit]): 分割成列表。join(iterable): 连接可迭代对象。var = "hello and python and hello world"
print(var.replace("and", "和")) # hello 和 python 和 hello world
print(var.split("and")) # ['hello ', ' python ', ' hello world']
list1 = ["hello", "python"]
print("__".join(list1)) # hello__python
capitalize(): 首字母大写。title(): 单词首字母大写。upper(), lower(): 全转大写/小写。strip(), lstrip(), rstrip(): 去除两侧/左侧/右侧空白。var = " hello world "
print(var.strip()) # hello world
print(var.lower()) # hello world
ljust(width[, fillchar]): 左对齐。rjust(width[, fillchar]): 右对齐。center(width[, fillchar]): 居中对齐。var = "hello"
print(var.ljust(10, "_")) # hello_____
print(var.center(10, "_")) # __hello___
startswith(prefix[, start[, end]]): 是否以指定前缀开头。endswith(suffix[, start[, end]]): 是否以指定后缀结尾。isalpha(): 仅字母。isdigit(): 仅数字。isalnum(): 字母或数字。isspace(): 仅空白。mystr = "12345"
print(mystr.isdigit()) # True
print(mystr.isalpha()) # False
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
+ | 连接 | "A" + "B" | "AB" |
* | 重复 | "A" * 3 | "AAA" |
in | 成员检查 | "A" in "ABC" | True |
not in | 非成员检查 | "D" not in "ABC" | True |
% | 格式化 | "Hi %s" % "Tom" | "Hi Tom" |
Python 字符串是不可变类型。这意味着不能直接修改字符串中的某个字符。例如 s[0] = 'a' 会报错。所有看似'修改'的操作(如 replace)实际上都是创建了新字符串对象。
Python 3 默认使用 Unicode 编码。特殊字符需要使用转义符,如 \n (换行)、\t (制表符)。原始字符串可使用 r"" 避免转义。
path = r"C:\new\test" # 不会将 \n 识别为换行
"".join(list) 而非 + 循环,因为每次 + 都会创建新对象。本文涵盖了 Python 字符串的核心知识点,建议结合代码练习加深理解。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online