1. 基本信息
方法 说明 len(str)
返回字符串的长度(不是方法,是内置函数) +
字符串拼接 *
字符串重复 str.format()
字符串格式化(如 "Hello, {}".format("world")
)
2. 查找与统计
方法 说明 str.count(sub)
统计子串出现次数 str.index(sub)
查找子串位置,找不到报错 str.find(sub)
查找子串位置,找不到返回 -1
3. 大小写转换
方法 说明 str.capitalize()
首字母大写,其余小写 str.upper()
全部转为大写 str.lower()
全部转为小写 str.swapcase()
大小写互换 str.title()
每个单词首字母大写
4. 对齐与填充
方法 说明 str.center(width)
居中,左右填充空格 str.ljust(width)
左对齐,右边填充空格 str.rjust(width)
右对齐,左边填充空格 str.zfill(width)
右对齐,左边填充 0
5. 判断开头结尾
方法 说明 str.startswith(sub)
判断是否以某子串开头 str.endswith(sub)
判断是否以某子串结尾
6. 切割与拼接
方法 说明 str.split(sep)
按指定分隔符切割,返回列表 sep.join(list)
用指定字符串连接列表元素,返回字符串
7. 去除空白字符
方法 说明 str.strip()
去除首尾空白字符 str.lstrip()
去除左边空白字符 str.rstrip()
去除右边空白字符
8. 替换
方法 说明 str.replace(old, new)
替换字符串中的子串
字符串常用方法案例
1. 基本信息
长度、拼接、重复、格式化
s = "hello"
print(len(s)) # 输出: 5
s2 = "world"
print(s + " " + s2) # 输出: hello world
print(s * 3) # 输出: hellohellohello
print("Hello, {}".format("Alice")) # 输出: Hello, Alice
2. 查找与统计
count、index、find
s = "banana"
print(s.count("a")) # 输出: 3
print(s.index("na")) # 输出: 2
# print(s.index("x")) # 报错: ValueError
print(s.find("na")) # 输出: 2
print(s.find("x")) # 输出: -1
3. 大小写转换
capitalize、upper、lower、swapcase、title
s = "hello world"
print(s.capitalize()) # 输出: Hello world
print(s.upper()) # 输出: HELLO WORLD
print(s.lower()) # 输出: hello world
print(s.swapcase()) # 输出: HELLO WORLD
print(s.title()) # 输出: Hello World
4. 对齐与填充
center、ljust、rjust、zfill
s = "abc"
print(s.center(10)) # 输出: ' abc '
print(s.ljust(10)) # 输出: 'abc '
print(s.rjust(10)) # 输出: ' abc'
print(s.zfill(10)) # 输出: '0000000abc'
5. 判断开头结尾
startswith、endswith
s = "hello world"
print(s.startswith("hello")) # 输出: True
print(s.endswith("world")) # 输出: True
6. 切割与拼接
split、join
s = "apple,banana,orange"
print(s.split(",")) # 输出: ['apple', 'banana', 'orange']
lst = ['apple', 'banana', 'orange']
print("-".join(lst)) # 输出: apple-banana-orange
7. 去除空白字符
strip、lstrip、rstrip
s = " hello world "
print(s.strip()) # 输出: 'hello world'
print(s.lstrip()) # 输出: 'hello world '
print(s.rstrip()) # 输出: ' hello world'
8. 替换
replace
s = "I like apples"
print(s.replace("apples", "bananas")) # 输出: I like bananas
总结
多练习 :亲自运行这些代码,加深理解。
多应用 :在实际项目中尝试使用这些方法。
多总结 :定期回顾,形成自己的知识体系。