哪个cms做企业网站好网站如何做优化推广
Python3 【字符串】:方法和函数使用示例手册
Python 提供了丰富的字符串处理方法和函数,以下是一些常用的方法和函数分类整理,并提供详细使用示例,简单易懂,值得收藏。
1. 字符串大小写转换
str.upper():将字符串转换为大写。str.lower():将字符串转换为小写。str.title():将每个单词的首字母大写。str.capitalize():将字符串的第一个字符大写。str.swapcase():交换字符串中的大小写。
s = "hello world"
print(s.upper())        # 输出 "HELLO WORLD"
print(s.title())        # 输出 "Hello World"
print(s.capitalize())   # 输出 "Hello world"
 
2. 字符串查找与替换
str.find(sub):返回子字符串sub第一次出现的索引,未找到返回-1。str.rfind(sub):从右侧开始查找子字符串。str.index(sub):与find()类似,但未找到时会抛出ValueError。str.rindex(sub):从右侧开始查找。str.replace(old, new):将字符串中的old替换为new。str.count(sub):返回子字符串sub出现的次数。
s = "hello world"
print(s.find("world"))  # 输出 6
print(s.replace("world", "Python"))  # 输出 "hello Python"
print(s.count("l"))     # 输出 3
 
3. 字符串分割与连接
str.split(sep):根据分隔符sep将字符串分割为列表。str.rsplit(sep):从右侧开始分割。str.splitlines():按行分割字符串。str.join(iterable):将可迭代对象中的元素用字符串连接。
s = "hello,world,python"
print(s.split(","))     # 输出 ['hello', 'world', 'python']
print("-".join(["a", "b", "c"]))  # 输出 "a-b-c"
 
4. 字符串去除空白与填充
str.strip():去除字符串两端的空白字符。str.lstrip():去除左侧空白字符。str.rstrip():去除右侧空白字符。str.center(width):将字符串居中并用空格填充到指定宽度。str.ljust(width):左对齐并用空格填充。str.rjust(width):右对齐并用空格填充。str.zfill(width):用0填充字符串到指定宽度。
s = "  hello  "
print(s.strip())        # 输出 "hello"
print(s.center(10))     # 输出 "  hello   "
print("42".zfill(5))    # 输出 "00042"
 
5. 字符串检查
str.startswith(prefix):检查字符串是否以prefix开头。str.endswith(suffix):检查字符串是否以suffix结尾。str.isalpha():检查字符串是否只包含字母。str.isdigit():检查字符串是否只包含数字。str.isalnum():检查字符串是否只包含字母和数字。str.isspace():检查字符串是否只包含空白字符。str.islower():检查字符串是否全为小写。str.isupper():检查字符串是否全为大写。
s = "hello123"
print(s.startswith("he"))  # 输出 True
print(s.isalnum())         # 输出 True
print(s.isdigit())         # 输出 False
 
6. 字符串格式化
str.format():格式化字符串。f-string(Python 3.6+):更简洁的格式化方式。str % values:旧式格式化(不推荐)。
name = "Alice"
age = 25
print("Name: {}, Age: {}".format(name, age))  # 输出 "Name: Alice, Age: 25"
print(f"Name: {name}, Age: {age}")            # 输出 "Name: Alice, Age: 25"
 
7. 字符串编码与解码
str.encode(encoding):将字符串编码为字节。bytes.decode(encoding):将字节解码为字符串。
s = "hello"
encoded = s.encode("utf-8")  # 编码为字节
print(encoded)               # 输出 b'hello'
decoded = encoded.decode("utf-8")  # 解码为字符串
print(decoded)               # 输出 "hello"
 
8. 其他常用方法
len(str):返回字符串的长度。str[::-1]:反转字符串。str in str2:检查字符串是否包含子字符串。str * n:重复字符串n次。
s = "hello"
print(len(s))        # 输出 5
print(s[::-1])       # 输出 "olleh"
print("he" in s)     # 输出 True
print(s * 3)         # 输出 "hellohellohello"
 
9. 字符串与列表的转换
list(str):将字符串转换为字符列表。"".join(list):将字符列表合并为字符串。
s = "hello"
char_list = list(s)  # 转换为列表 ['h', 'e', 'l', 'l', 'o']
new_s = "".join(char_list)  # 合并为字符串 "hello"
 
10. 字符串的 Unicode 处理
ord(char):返回字符的 Unicode 码点。chr(code):返回 Unicode 码点对应的字符。
print(ord("A"))  # 输出 65
print(chr(65))   # 输出 "A"
 
11. 字符串的切片操作
字符串切片是 Python 中非常强大且常用的功能,它允许你从字符串中提取子字符串。切片的基本语法是:
string[start:stop:step]
 
start:起始索引(包含)。stop:结束索引(不包含)。step:步长(可选,默认为 1)。
以下是更多关于切片的例子:
(1) 基本切片
s = "Python Programming"# 提取索引 0 到 5 的字符(不包含索引 6)
print(s[0:6])  # 输出 "Python"# 提取索引 7 到 18 的字符
print(s[7:18])  # 输出 "Programming"
 
(2) 省略起始或结束索引
- 如果省略 
start,默认从字符串开头开始。 - 如果省略 
stop,默认到字符串末尾结束。 
s = "Python Programming"# 从开头到索引 5
print(s[:6])  # 输出 "Python"# 从索引 7 到末尾
print(s[7:])  # 输出 "Programming"# 提取整个字符串
print(s[:])  # 输出 "Python Programming"
 
(3) 使用负索引
负索引表示从字符串末尾开始计数(-1 是最后一个字符)。
s = "Python Programming"# 提取最后 5 个字符
print(s[-5:])  # 输出 "mming"# 提取从索引 -12 到 -1 的字符
print(s[-12:-1])  # 输出 "Programmin"
 
(4) 使用步长
步长 step 控制切片的间隔。
s = "Python Programming"# 提取所有字符,步长为 2
print(s[::2])  # 输出 "Pto rgamn"# 反转字符串
print(s[::-1])  # 输出 "gnimmargorP nohtyP"# 从索引 0 到 10,步长为 3
print(s[0:10:3])  # 输出 "Phr"
 
(5) 复杂切片
结合起始、结束和步长,可以实现更复杂的切片。
s = "Python Programming"# 从索引 2 到 12,步长为 2
print(s[2:12:2])  # 输出 "to rg"# 从索引 -10 到 -1,步长为 3
print(s[-10:-1:3])  # 输出 "rgn"
 
(6) 切片与字符串操作结合
切片可以与其他字符串操作结合使用。
s = "Python Programming"# 提取前 6 个字符并转换为大写
print(s[:6].upper())  # 输出 "PYTHON"# 提取最后 5 个字符并反转
print(s[-5:][::-1])  # 输出 "gnimm"
 
(7) 切片与条件结合
可以根据条件动态调整切片的范围。
s = "Python Programming"# 提取字符串的前半部分
half_length = len(s) // 2
print(s[:half_length])  # 输出 "Python Pro"# 提取字符串的后半部分
print(s[half_length:])  # 输出 "gramming"
 
(8) 多层切片
可以对切片结果再次切片。
s = "Python Programming"# 先提取 "Programming",再提取前 5 个字符
print(s[7:][:5])  # 输出 "Progr"
 
总结
Python 的字符串处理功能非常强大,涵盖了大小写转换、查找替换、分割连接、格式化、编码解码、切片处理等多种操作。掌握这些方法和函数,可以高效地处理各种字符串任务!
