字符串是不可变对象
任何对字符串的修改操作(如替换、删除、拼接)都会返回新的字符串对象,而不是修改原字符串。
原字符串在内存中的值保持不变。
字符串的常用方法,字符串用得最多的类型之一
查看函数的帮助:help(函数名)
msg = "hello world"
help(msg.count)
查看对象有什么方法/功能/函数:dir(对象名)
print(dir(msg))
[‘__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(msg.isalpha()) # True
print("你好".isalpha()) # True(中文也是字母)
print("hello".isalpha()) # False
判断字符串是否完全由字母或数字字符组成
print("Hello".isalnum()) # True
print("12345".isalnum()) # True
print("1a".isalnum()) # True
print(msg.isalnum()) # Fasle(包含空格)
判断字符串是否完全由数字组成,不仅检测 ASCII 数字(0-9),还包括其他 Unicode 数字字符(①②③),如罗马数字(VII)、上标数字 (2 3)等。
print("123".isdigit()) # True
print("一二三".isdigit()) # False
判断字符串是否完全由数值字符组成
isnumeric() 支持以下字符:
十进制数字(如 0-9)
Unicode 数字(如 ①②③、Ⅷ)
分数(如 ½、¾)
下标和上标数字(如 ²、₃)
罗马数字(如 Ⅰ、Ⅻ)
中文数字(一、二、三)
中文数字单位(如 十、百、千、万、亿)
print("一二三零百千亿".isnumeric()) # True
判断字符串是否只包含十进制数字字符(0-9)
print("12345".isdecimal()) # True
print("123a".isdecimal()) # False
print("-123".isdecimal()) # False
判断字符串是否只包含空白字符
isspace()能识别以下 Unicode 空白字符:
print(" ".isspace()) # True
print("\t\n\r".isspace()) # True
print(" a ".isspace()) # False
print("".isspace()) # False
判断字符串是否符合标题格式
标题格式:字符串中每个单词的首字母都是大写,其余字母都是小写
print("Hello World".istitle()) # True
print("Hello WORLD".istitle()) # False
判断字符串是否符合Python 标识符(变量名)的命名规则
print("VarName".isidentifier()) # True
print("123var".isidentifier()) # False
print("hello world".isidentifier()) # False(包含空格)
print("if".isidentifier()) # False(保留关键字)
islower 判断字符串中的所有字母字符是否全为小写
isupper 判断字符串中的所有字母字符是否全为大写
print("abc".isupper()) # True
print("aBc".islower()) # False
print("abc".isupper()) # False
startswith 判断字符串是否以特定前缀开头
endwith 判断字符串是否以特定后缀结尾
print("hello".startswith("he")) # True
print("hello".startswith("hee")) # False
print("hello".startswith("ll", 2)) # True(从索引2开始)
print("hello".startswith("ll", 0, 3)) # False(范围0-2不包含"ll")
print("hello".endswith("ll", 0, 4)) # True(范围0-3以"ll"结尾)
多前缀 / 后缀检查(元组)
url = "https://example.com"
print(url.startswith(("http://", "https://"))) # True
filename = "data.csv"
print(filename.endswith((".txt", ".csv", ".json"))) # True
lower 将字符串中的所有字母转换为小写
upper 将字符串中的所有字母转换为大写
print("aBc".lower()) # abc
print("abC".upper()) # ABC
将字符串中每个单词的首字母转换为大写,其余字母转换为小写
任何非字母字符(如空格、数字、符号)被视为单词的分隔符
print("aBc1中国".title()) # Abc1中国
print("hElLo wOrLd".title()) # Hello World
将字符串的首字母转换为大写,其余字母转换为小写
print("hElLo wOrLd".capitalize()) # Hello world
print("123aBc".capitalize()) # 123abc
将字符串中的大写字母转为小写,小写字母转为大写,而其他字符保持不变(大小写互换)
string.swapcase()
print("Hello World".swapcase()) # hELLO wORLD
用于统计序列中某个元素出现的次数
msg = "hello world"
print(msg.count("o")) # 2
print(msg.count("Hello")) # 0
print(msg.count("hello")) # 1
print(msg.count("o", 5)) # 1
print(msg.count("o", 2, 10)) # 2
用于从左侧开始查找子串,并返回其首次出现的索引位置,索引从 0 开始。如果子串不存在,抛出 ValueError 异常
print("hello".index("l")) # 2
print("hello".index("l", 3)) # 3
print("banana".rindex("a")) # 5
用于从左侧开始查找子串,并返回其首次出现的索引位置。如果子串不存在,则返回 -1
print("hello".find("l")) # 2
print("hello".find("x")) # -1
将字符串中的指定子串替换为新的字符串
print("Hello WOrld".replace("O", "o")) # Hello World
print("banana".replace("a", "X", 2)) # bXnXna
用于去除字符串首尾的指定字符(默认移除空白字符)
string.strip([chars])
print(" Jack ".strip()) # Jack
print(".Jack ".lstrip(".")) # Jack
print(" Jack#".rstrip("#")) # Jack
去除字符串开头的指定前缀/后缀
必须完全匹配才会去除
print("unhappy".removeprefix("un")) # happy
print("unhappy".removesuffix("happy")) # un
将字符串按指定分隔符分割成多个子字符串,并返回一个列表
msg = " a b c d e f g h i "
result = msg.split()
print(result) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print("a,b,c,d".split(",", 1)) # 分割1次,['a', 'b,c,d']
print("a,b,c,d".rsplit(",", 1)) # 从右侧分割1次,['a,b,c', 'd']
按行分割(处理 \n、\r、\r\n 等)
splitlines() 能识别以下换行符:
print("Line 1\nLine 2\nLine 3".splitlines()) # ['Line 1', 'Line 2', 'Line 3']
print("Line 1\nLine 2\nLine 3".splitlines(True)) # 保留换行符,['Line 1\n', 'Line 2\n', 'Line 3']
按指定分隔符将字符串分割为三部分,并返回一个元组
print("key:value".partition(":")) # ('key', ':', 'value')
# 分隔符不存在,返回原字符串和两个空字符串
print("hello".partition("x")) # ('hello', '', '')
# 多个分隔符,仅分割第一个匹配的分隔符
print("a:b:c".partition(":")) # ('a', ':', 'b:c')
print("a,b,c".rpartition(",")) # ('a,b', ',', 'c')
将可迭代对象(如列表、元组)中的元素连接成一个字符串
print(" ".join(["Hello", "World"])) # Hello World
print("".join(["a", "b", "c"])) # abc
# 元组、集合转字符串
print(":".join(("a", "b", "c"))) # "a:b:c"
print(" ".join({"apple", "banana"})) # 注意:集合是无序的,可能是 "apple banana" 或 "banana apple"
# 字符串转字符串(重新连接)
print("-".join("hello")) # "h-e-l-l-o"
# 单个元素直接返回,不加连接符
print("-".join(["apple"])) # "apple"
鸭子类型(Duck Typing)是一种编程风格,它不关注对象的具体类型,而是关注对象是否实现了特定的方法或协议。
是指可以被遍历(迭代)的对象
支持 for 循环和 iter()
字符串,列表,元组,字典,集合都是可迭代对象
方法
__iter__():返回一个迭代器(Iterator)对象。
__getitem__():支持通过整数索引访问元素(从 0 开始)
for char in "hello":
print(char, end=" ") # 输出: h e l l o
for num in [1, 2, 3]:
print(num, end=" ") # 输出: 1 2 3
for key in {"a": 1, "b": 2}:
print(key, end=" ") # 输出: a b
# 自定义可迭代类
class MyRange:
def __init__(self, n):
self.n = n
def __iter__(self):
i = 0
while i < self.n:
yield i # 使用生成器简化迭代器实现
i += 1
for i in MyRange(3):
print(i, end=" ") # 输出: 0 1 2
是一种可以包含其他对象的对象,它们实现了特定的方法来支持元素的存储、访问和管理
字符串、列表、集合都是容器
方法
__contains__(self, item):支持 in 操作符,检查元素是否存在
__len__(self):支持 len() 函数,返回容器长度
# 判断子串
print("h" in "hello") # 输出: True
print(1 in [1, 2, 3]) # 输出: True
print(1 in {1, 2, 3}) # 输出: True
print("key" in {"key": 1}) # 输出: True
# 查看字符串长度
print(len("abc ")) # 输出:4(包含空格)
# 自定义容器类
class MyList:
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items # 委托给内置列表
def __len__(self):
return len(self.items) # 委托给内置列表
my_list = MyList([10, 20, 30])
print(20 in my_list) # 输出: True
print(len(my_list)) # 输出: 3
用于管理资源的对象,确保资源在使用后被正确释放。上下文管理器通过 with 语句使用
方法
__enter__():进入上下文时调用,返回资源对象。
__exit__():退出上下文时调用,负责清理资源。
# 文件对象是上下文管理器
with open("test.txt", "w") as f:
f.write("hello") # 自动关闭文件
# 线程锁也是上下文管理器
import threading
lock = threading.Lock()
with lock:
# 自动获取和释放锁
print("Locked")
# 自定义上下文管理器
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self # 返回值绑定到 as 后的变量
def __exit__(self, exc_type, exc_val, exc_tb):
import time
elapsed = time.time() - self.start
print(f"耗时: {elapsed:.2f}秒")
with Timer():
sum(i for i in range(10**7)) # 输出: 耗时: 0.47秒
可以像函数一样被调用(使用 () 运算符)的对象或实体
函数、方法、类都是可调用对象
def add(a, b):
return a + b
print(add(1, 2)) # 输出: 3
class Adder:
def __call__(self, a, b):
return a + b
adder = Adder()
print(adder(3, 4)) # 输出: 7 (像函数一样调用实例)
# 自定义可调用类
class Counter:
def __init__(self):
self.count = 0
def __call__(self):
self.count += 1
return self.count
counter = Counter()
print(counter()) # 输出: 1
print(counter()) # 输出: 2
是一种实现了文件接口的对象,也称为类文件对象或流对象这类对象支持文件的基本操作(如读取、写入、关闭),但不一定对应物理文件,可能是内存中的数据、网络连接或其他数据源
方法
# 标准库中的 StringIO 模拟文件操作
from io import StringIO
f = StringIO()
f.write("hello") # 写入内存
print(f.getvalue()) # 输出: hello
f.seek(0) # 移动文件指针到开头
print(f.read()) # 输出: hello
# 自定义文件类
class LogFile:
def __init__(self, filename):
self.filename = filename
def write(self, data):
with open(self.filename, "a") as f:
f.write(f"[LOG] {data}\n")
def read(self):
with open(self.filename, "r") as f:
return f.read()
log = LogFile("app.log")
log.write("User logged in")
print(log.read()) # 输出: [LOG] User logged in
是一种可迭代的容器,支持通过索引访问元素
通用操作:
s = "hello" # 字符串
print(s[0]) # 输出: h
lst = [1, 2, 3] # 列表
print(lst[1]) # 输出: 2
t = (4, 5, 6) # 元组
print(t[2]) # 输出: 6
# 自定义序列类
class MySequence:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index] # 支持索引和切片
seq = MySequence([10, 20, 30])
print(seq[0]) # 输出: 10
print(seq[1:]) # 输出: [20, 30]
是指实现了比较运算符(如 <、>、== 等)的对象。通过实现这些方法,对象可以用于排序、最大 / 最小值查找、条件判断等操作
常用的比较方法有:
# 列表、元组、字符串都可以用 max()
print(max([3, 1, 4])) # 4(列表)
print(max((5, 2, 9))) # 9(元组)
print(max("hello")) # 'o'(字符串)
# 自定义类实现 __lt__() 也可以用 max()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
return self.age < other.age
people = [Person("Alice", 25), Person("Bob", 30)]
print(max(people).name) # "Bob"(按年龄比较)
number = input("请输入一个整数:")
if number.isdigit():
if int(number) % 2 == 0:
print(f"{number}是偶数")
else:
print(f"{number}是奇数")
else:
print("请输入整数")
从键盘接收一个字符串,将字符串的字母和数字提取出来
string = input("请输入一个字符串:") # 输入:ab12c3
nums = ''
alpha = ''
for s in string:
if s.isalpha():
alpha += s
elif s.isdigit():
nums += s
print(nums) # 输出:123
print(alpha) # 输出:abc
从键盘输入密码,检查密码强度,最高分5分,有1个不满足条件减1分,列出未满足条件的规则
password = input("请输入密码:")
score = 5
if len(password) < 8:
score = score - 1
print("密码长度不足")
if password.count(" ") > 0:
print("密码中包含空格")
score = score - 1
uppers = 0
lowers = 0
digits = 0
others = 0
for c in password:
if c.isupper():
uppers = 1
elif c.islower():
lowers = 1
elif c.isdigit():
digits = 1
else:
others = 1
if uppers + lowers + digits + others < 3:
score = score - 1
print("字符类型不足3种")
print("当前密码得分:", score)
num = 66
for i in range(5):
number = input("请输入猜的数字:")
if number.isdigit():
if int(number) > num:
print("再往小猜一点点")
elif int(number) < num:
print("再往大猜一点点")
else:
print("恭喜你猜对了!")
break
else:
print("请输入数字")
else:
print("机会已经用完,游戏结束!")
# 无限循环 (while True)
num = 66
while True:
n = input("猜猜是多少?(输入Q|q退出)")
if n.lower().strip() == "q":
print("游戏结束!")
break
if n.isdigit():
if int(n) == num:
print("恭喜你猜对了!")
break
elif int(n) < num:
print("再往大猜一点点")
else:
print("再往小猜一点点")
else:
print("请输入一个数字")
sensitive_word = "abc"
msg = "hello world abcdefgabc"
# 判断是否存在敏感词,存在敏感词则替换,不存在则保持原输出
if sensitive_word in msg:
msg_replace = msg.replace(sensitive_word, "*"*len(sensitive_word))
print(msg_replace)
else:
print(msg)
msg = "abAdef"
msg_caesar_cipher = ''
for i in msg:
# ord()返回单个字符的 Unicode 码点
msg_caesar_cipher += chr(ord(i) + 3)
print(msg_caesar_cipher)
# 定义最长连续子串的起始字符和长度
max_char = s[0]
max_length = 1
current_char = s[0]
current_length = 1
# 从第二个字符开始遍历
for c in s[1:]:
if c == current_char:
current_length += 1
if current_length > max_length:
max_length = current_length
max_char = current_char
else:
current_char = c
current_length = 1
print(f"{s}的最大子串为:{max_char * max_length}")