Python
基础语法
01概念
02安装
03变量
04字符串
05数
06常量与注释
07列表
08元组
09if语句
10字典
11集合
12复合数据类型对比
13推导式
14用户输入
15while循环
16函数
17类
18面向对象编程
19文件操作
20异常处理
21日期和时间
22魔术方法
23内置函数
24线程
25并发&并行
26正则表达式
27迭代器
28装饰器
29生成器
30上下文管理器
31函数式编程
32闭包
33解包
34工具库
35连接关系型数据库
36虚拟环境
37异步编程
网络爬虫
01urllib库[了解]
02requests库
03数据交换格式
04解析库
05lxml
06Beautiful Soup
07Xpath语法
08动态网页的处理
-
+
首页
04字符串
## 字符串 在 Python 中,字符串(String) 是最常用的数据类型之一,简单来说,它就是由一系列字符(比如字母、数字、符号等)组成的文本。无论是我们平时看到的文字、句子,还是程序中的文本信息,在 Python 中几乎都用字符串来表示。 在python中,用引号引起的都是字符串,引号可以是单引号也可以是双引号,注意是英文的单引号或者双引号。 ```python >>> print("Hello world") Hello world >>> print('Hello world') Hello world ``` ## 相关操作 **同时给多个变量赋值** ```python >>> a,b,c = 1,2,3 >>> print(b) 2 >>> print(c) 3 >>> print(a) 1 ``` **修改大小写** 示例: ```python >>> name = "maolin101" >>> print(name.title()) Maolin101 >>> print(name.upper()) MAOLIN101 >>> name = "MAOLIN101" >>> print(name) MAOLIN101 >>> print(name.lower()) maolin101 ``` 最开始变量name指向的全小写的字符串“maolin101”,print函数的功能是将内容打印在屏幕中,name.title()表示的是使用name变量的title()方法。 print(name.title())的整体意思就是让python对name变量执行title()方法指定的操作,然后再将操作之后的内容打印在屏幕中。 title()方法的作用是以首字母大写的方式显示每一个单词,upper()方法的作用是将所有字母转换为大写,lower()方法的作用是将所有字母转换为小写。 **使用制表符或者换行符号来添加空白** 在编程中,空白泛指任何非打印字符,如空格、制表符和换行符,可以使用空白来组织输出,让用户阅读起来更容易。 ```python >>> print("Pythonisgood") Pythonisgood >>> print("Python\tis\tgood") Python is good >>> print("Python\nis\ngood") Python is good ``` **在字符串中添加单双引号** 如果我需要打印的字符串是:"maolin101 'is' good" ```python >>> name = "maolin101 is good" >>> print(name) maolin101 is good >>> name = "\"maolin101 'is' good\"" >>> print(name) "maolin101 'is' good" ``` 当字符串中需要包含一些 “特殊符号”(比如引号、换行符)时,直接写会导致歧义,这时候需要用转义字符(以 \ 开头)。 **删除空白** 在程序中,额外的空白会令人迷惑,例如"python"和"python ",对程序来说,是两个不同的字符串。 确保字符串的右侧没有空白,可以使用rstrip()方法。 ```python >>> name = "maolin101 " >>> print(name.rstrip()) maolin101 ``` 删除字符串的左侧空白使用lstrip(),同时删除字符串两端使用strip()。 ```python >>> name = " maolin101" >>> print(name.lstrip()) maolin101 >>> name = " maolin101 " >>> print(name.strip()) maolin101 ``` **删除前缀** removeprefix()方法,可以删除前缀,只需要在括号里面填写需要删除的前缀字符串即可。 ```python >>> domain = "https://maolin101.com" >>> print(domain.removeprefix('https://')) maolin101.com ``` **计算字符长度** len()方法,可以计算字符串的长度。 ```python >>> domain = "https://maolin101.com" >>> print(len(domain)) 21 ``` **分割与连接** split(分隔符):按指定分隔符把字符串拆成列表(默认按空格分割) join(列表):用字符串把列表中的元素连接成新字符串 ```python >>> s = "apple,banana,orange" >>> print(s.split(",")) ['apple', 'banana', 'orange'] >>> words = ["I", "love", "Python"] >>> print("".join(words)) IlovePython ``` **索引** 字符串是一种 “序列”(可以理解为 “有序排列的字符集合”),因此可以像操作列表一样,通过索引获取单个字符,通过切片获取子字符串。 - 每个字符在字符串中都有一个 “位置编号”,称为索引。 - 索引从0 开始(第一个字符索引为 0,第二个为 1,以此类推)。 - 也可以用负数索引(最后一个字符索引为 - 1,倒数第二个为 - 2,以此类推)。 ```python >>> s = "Python" >>> print(s[0]) P >>> print(s[3]) h >>> print(s[-1]) n ``` **切片(获取子字符串)** 切片是指从字符串中截取一部分字符,语法:字符串[start: end :step] - start:起始位置(包含该位置,默认 0) - end:结束位置(不包含该位置,默认字符串长度) - step:步长(每隔几个字符取一次,默认 1,负数表示反向截取) ```python >>> s = "abcdefgh" >>> print(s[1:4]) bcd >>> print(s[3:]) defgh >>> print(s[:4]) abcd >>> print(s[0:7:2]) aceg >>> print(s[::-1]) hgfedcba ``` **拼接** 用 +可以把多个字符串连接成一个新字符串。 ```python >>> a = "Hello" >>> b = "World" >>> c = a + " " + b >>> print(c) Hello World ``` 注意:字符串不能和数字直接拼接,需要先用 str() 把数字转为字符串。 **重复** 用 * 可以让字符串重复指定次数。 ```python >>> star = "$" >>> print(star * 5) $$$$$ ``` **成员判断(in /not in)** 用 in 判断一个子字符串是否在原字符串中,not in 则相反。 ```python >>> s = "I love Python" >>> print("love" in s) True >>> print("java" in s) False >>> print("Python" not in s) False ``` **常用的字符串方法** 每个方法都有明确的功能,调用方式都是 字符串.方法名(参数): | 方法 | 功能描述 | 示例 | | ------------------ | ------------------------------------------------------ | ------------------------------------------------ | | upper() | 把所有字符转为大写 | "hello".upper() → "HELLO" | | lower() | 把所有字符转为小写 | "HELLO".lower() → "hello" | | title() | 每个单词首字母大写(标题格式) | "hello world".title() → "Hello World" | | strip() | 去除字符串两端的空格(包括换行\n、制表符\t) | " hello ".strip() → "hello" | | lstrip() | 只去除左侧的空格 | " hello ".lstrip() → "hello " | | rstrip() | 只去除右侧的空格 | " hello ".rstrip() → " hello" | | split(sep) | 按指定分隔符sep分割字符串,返回列表(默认按空格分割) | "a,b,c".split(",") → ["a", "b", "c"] | | join(iterable) | 用字符串连接可迭代对象(如列表)中的元素,返回新字符串 | "-".join(["a", "b", "c"]) → "a-b-c" | | replace(old, new) | 把所有old子串替换为new子串 | "apple".replace("p", "P") → "aPPle" | | find(sub) | 查找sub子串第一次出现的索引,找不到返回-1 | "hello".find("l") → 2 | | index(sub) | 类似find(),但找不到会报错 | "hello".index("x") → 报错 | | startswith(prefix) | 判断字符串是否以prefix开头(返回True/False) | "hello".startswith("he") → True | | endswith(suffix) | 判断字符串是否以suffix结尾(返回True/False) | "hello".endswith("lo") → True | | count(sub) | 统计sub子串在字符串中出现的次数 | "aaa".count("a") → 3 | | isdigit() | 判断字符串是否全是数字(返回True/False) | "123".isdigit() → True;"12a3".isdigit() → False | | isalpha() | 判断字符串是否全是字母(返回True/False) | "abc".isalpha() → True;"ab1c".isalpha() → False | 如果想知道字符串有哪些方法(包括不常用的),可以用dir()函数查看所有方法名。 ```python >>> print(dir("")) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> print(dir(str)) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] ``` 如果不知道方法如何使用,可以使用help()。 ```python >>> help("".strip) Help on built-in function strip: strip(chars=None, /) method of builtins.str instance Return a copy of the string with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. ``` ## 字符串总结 字符串是 Python 中处理文本的核心类型,记住这几个关键点: - 用引号创建,三引号支持多行文本; - 不可变:不能直接修改单个字符,只能创建新字符串; - 序列特性:可通过索引取单个字符,通过切片取子字符串; - 常用操作:拼接(+)、重复(*)、判断包含(in)、求长度(len ()); - 常用方法:大小写转换、去空格、分割 / 连接、替换、查找等。 注意:字符串一旦创建,它所包含的字符就不能被直接修改、删除或替换。无论你想改变字符串中的某个字符、删除某个字符,还是替换某个字符,都无法直接对原字符串进行操作 —— 必须通过创建一个新的字符串来实现 “修改” 效果,而原字符串本身始终保持不变。 ```python >>> s = "hello" >>> s[0] = "H" Traceback (most recent call last): File "<python-input-56>", line 1, in <module> s[0] = "H" ~^^^ TypeError: 'str' object does not support item assignment ```
毛林
2025年9月7日 11:45
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
PDF文档(打印)
分享
链接
类型
密码
更新密码