字符串是 Python 中最常用的数据类型之一,用于表示文本信息。Python 中的字符串是不可变的序列,可以使用单引号(')或双引号(")创建。
var1 = 'Hello World!'
var2 = "Python"
1. Python 访问字符串中的值
Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。
可以通过索引和切片来访问字符串中的值。
Python 访问子字符串,可以使用方括号 [] 来截取字符串,字符串的截取的语法格式如下:
s = "Hello, Python!"
# 通过索引访问单个字符
print(s[0]) # 输出: H
print(s[-1]) # 输出: ! (负索引表示从末尾开始)
# 通过切片访问子字符串
print(s[0:5]) # 输出: Hello (从索引0到4)
print(s[7:]) # 输出: Python! (从索引7到末尾)
print(s[:5]) # 输出: Hello (从开始到索引4)
print(s[::2]) # 输出: Hlo yhn (步长为2)
2. Python 字符串更新
由于字符串是不可变的,不能直接修改字符串中的某个字符,但可以通过创建新字符串来实现"更新"。
s = "Hello, World!"
# 替换字符 - 创建新字符串
s = s[:7] + "Python" + s[-1]
print(s) # 输出: Hello, Python!
# 拼接字符串
s1 = "Hello"
s2 = "Python"
s = s1 + ", " + s2 + "!"
print(s) # 输出: Hello, Python!
3. Python 转义字符
转义字符用于表示一些特殊字符:
转义字符 | 描述 | 实例 |
---|---|---|
\(在行尾时) | 续行符 |
>>> print("line1 \ ... line2 \ ... line3") line1 line2 line3 >>> |
\\ | 反斜杠符号 |
>>> print("\\") \ |
\' | 单引号 |
>>> print('\'') ' |
\" | 双引号 |
>>> print("\"") " |
\a | 响铃 |
>>> print("\a")执行后电脑有响声。 |
\b | 退格(Backspace) |
>>> print("Hello \b World!") Hello World! |
\000 | 空 |
>>> print("\000") >>> |
\n | 换行 |
>>> print("\n") >>> |
\v | 纵向制表符 |
>>> print("Hello \v World!") Hello World! >>> |
\t | 横向制表符 |
>>> print("Hello \t World!") Hello World! >>> |
\r | 回车,将 \r 后面的内容移到字符串开头,并逐一替换开头部分的字符,直至将 \r 后面的内容完全替换完成。 |
>>> print("Hello\rWorld!") World! >>> print('google runoob taobao\r123456') 123456 runoob taobao |
\f | 换页 |
>>> print("Hello \f World!") Hello World! >>> |
\yyy | 八进制数,y 代表 0~7 的字符,例如:\012 代表换行。 |
>>> print("\110\145\154\154\157\40\127\157\162\154\144\41") Hello World! |
\xyy | 十六进制数,以 \x 开头,y 代表的字符,例如:\x0a 代表换行 |
>>> print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21") Hello World! |
\other | 其它的字符以普通格式输出 |
print("这是\"引号\"") # 输出: 这是"引号"
print("第一行\n第二行") # 输出两行文本
print("C:\\Users\\Name") # 输出: C:\Users\Name
4. Python 字符串运算符
Python 提供了多种字符串运算符:
运算符 | 描述 | 示例 |
---|---|---|
+ | 字符串连接 | "Hello" + "World" → "HelloWorld" |
* | 重复字符串 | "Hi" * 3 → "HiHiHi" |
[] | 通过索引获取字符 | "Hello"[1] → 'e' |
[:] | 截取字符串 | "Hello"[1:4] → 'ell' |
in | 成员运算符 - 如果字符串中包含给定的字符返回 True | 'H' in "Hello" → True |
not in | 成员运算符 - 如果字符串中不包含给定的字符返回 True | 'h' not in "Hello" → False |
% | 格式字符串 | 见第5节 |
s1 = "Hello"
s2 = "Python"
print(s1 + " " + s2) # Hello Python
print(s1 * 3) # HelloHelloHello
print('H' in s1) # True
print('h' not in s1) # True
5. Python 字符串格式化
Python 支持多种字符串格式化方法:
5.1 % 格式化 (旧式格式化)
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
# 输出: My name is Alice and I'm 25 years old.
# 常用格式化符号:
# %s - 字符串
# %d - 十进制整数
# %f - 浮点数
# %.2f - 保留两位小数的浮点数
符 号 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
%E | 作用同%e,用科学计数法格式化浮点数 |
%g | %f和%e的简写 |
%G | %f 和 %E 的简写 |
%p | 用十六进制数格式化变量的地址 |
5.2 str.format() 方法 (Python 2.6+)
name = "Bob"
age = 30
print("My name is {} and I'm {} years old.".format(name, age))
# 输出: My name is Bob and I'm 30 years old.
# 带编号的占位符
print("{0} is {1} years old. {0} is a programmer.".format(name, age))
# 带名称的占位符
print("My name is {name} and I'm {age} years old.".format(name=name, age=age))
# 格式化数字
print("Pi is approximately {:.2f}".format(3.14159)) # 输出: Pi is approximately 3.14
6. f-string (Python 3.6+)
f-string 是 Python 3.6 引入的一种更简洁、更易读的字符串格式化方法:
f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去
name = "Charlie"
age = 35
print(f"My name is {name} and I'm {age} years old.")
# 输出: My name is Charlie and I'm 35 years old.
# 表达式计算
a = 5
b = 10
print(f"{a} + {b} = {a + b}") # 输出: 5 + 10 = 15
# 格式化数字
pi = 3.1415926
print(f"Pi is approximately {pi:.2f}") # 输出: Pi is approximately 3.14
7. Unicode 字符串
# 直接使用Unicode字符
print("你好,世界!") # 输出中文
# 使用Unicode转义序列
print("\u4f60\u597d") # 输出: 你好
# 编码与解码
s = "你好"
encoded = s.encode('utf-8') # 编码为字节
decoded = encoded.decode('utf-8') # 解码回字符串
print(encoded) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(decoded) # 你好
8. Python 的字符串内建函数
Python 提供了丰富的字符串方法:
8.1 大小写转换
s = "hello python"
print(s.capitalize()) # Hello python (首字母大写)
print(s.title()) # Hello Python (每个单词首字母大写)
print(s.upper()) # HELLO PYTHON (全部大写)
print(s.lower()) # hello python (全部小写)
print(s.swapcase()) # HELLO PYTHON (大小写互换)
8.2 查找与替换
s = "Hello, Python, Python"
# 查找
print(s.find("Python")) # 7 (返回第一次出现的索引)
print(s.rfind("Python")) # 14 (从右边开始查找)
print(s.index("Python")) # 7 (类似find,但找不到会报错)
print(s.count("Python")) # 2 (统计出现次数)
# 替换
print(s.replace("Python", "World")) # Hello, World, World
8.3 字符串判断
s = "123abc"
print(s.isalnum()) # True (字母或数字)
print(s.isalpha()) # False (纯字母)
print(s.isdigit()) # False (纯数字)
print(s.islower()) # True (全部小写)
print(s.isupper()) # False (全部大写)
print(s.isspace()) # False (纯空白字符)
print(s.startswith("123")) # True
print(s.endswith("abc")) # True
8.4 字符串分割与连接
s = "apple,banana,orange"
# 分割
print(s.split(",")) # ['apple', 'banana', 'orange']
print(s.partition(",")) # ('apple', ',', 'banana,orange')
# 连接
lst = ['apple', 'banana', 'orange']
print(",".join(lst)) # apple,banana,orange
8.5 去除空白字符
s = " hello "
print(s.strip()) # "hello" (去除两端空白)
print(s.lstrip()) # "hello " (去除左端空白)
print(s.rstrip()) # " hello" (去除右端空白)
8.6 其他常用方法
s = "hello"
print(len(s)) # 5 (字符串长度)
print(s.center(10, "*")) # **hello*** (居中填充)
print(s.zfill(10)) # 00000hello (左侧填充0)
序号 | 方法及描述 |
---|---|
1 |
capitalize() |
2 |
center(width, fillchar) 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。 |
3 |
count(str, beg= 0,end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数 |
4 |
bytes.decode(encoding="utf-8", errors="strict") Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。 |
5 |
encode(encoding='UTF-8',errors='strict') 以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace' |
6 |
endswith(suffix, beg=0, end=len(string)) |
7 |
expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。 |
8 |
find(str, beg=0, end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1 |
9 |
index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在字符串中会报一个异常。 |
10 |
isalnum() 检查字符串是否由字母和数字组成,即字符串中的所有字符都是字母或数字。如果字符串至少有一个字符,并且所有字符都是字母或数字,则返回 True;否则返回 False。 |
11 |
isalpha() 如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False |
12 |
isdigit() 如果字符串只包含数字则返回 True 否则返回 False.. |
13 |
islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False |
14 |
isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False |
15 |
isspace() 如果字符串中只包含空白,则返回 True,否则返回 False. |
16 |
istitle() 如果字符串是标题化的(见 title())则返回 True,否则返回 False |
17 |
isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False |
18 |
join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串 |
19 |
len(string) 返回字符串长度 |
20 |
ljust(width[, fillchar]) 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。 |
21 |
lower() 转换字符串中所有大写字符为小写. |
22 |
lstrip() 截掉字符串左边的空格或指定字符。 |
23 |
maketrans() 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 |
24 |
max(str) 返回字符串 str 中最大的字母。 |
25 |
min(str) 返回字符串 str 中最小的字母。 |
26 |
replace(old, new [, max]) 把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。 |
27 |
rfind(str, beg=0,end=len(string)) 类似于 find()函数,不过是从右边开始查找. |
28 |
rindex( str, beg=0, end=len(string)) 类似于 index(),不过是从右边开始. |
29 |
rjust(width,[, fillchar]) 返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串 |
30 |
rstrip() 删除字符串末尾的空格或指定字符。 |
31 |
split(str="", num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串 |
32 |
splitlines([keepends]) 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。 |
33 |
startswith(substr, beg=0,end=len(string)) 检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。 |
34 |
strip([chars]) 在字符串上执行 lstrip()和 rstrip() |
35 |
swapcase() 将字符串中大写转换为小写,小写转换为大写 |
36 |
title() 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle()) |
37 |
translate(table, deletechars="") 根据 table 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中 |
38 |
upper() 转换字符串中的小写字母为大写 |
39 |
zfill (width) 返回长度为 width 的字符串,原字符串右对齐,前面填充0 |
40 |
isdecimal() 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。 |
Python 的字符串功能非常强大,掌握这些基本操作可以大大提高处理文本数据的效率。