Python-字符串常用方法

Python-字符串常用方法

  • 前言
  • 一、字符串判断
    • 1.isalpha
    • 2.isalnum
    • 3.isdigit
    • 4.isnumeric
    • 5.isdecimal
    • 6.isspace
    • 7.istitle
    • 8.isidentifier
    • 9.islower,isupper
    • 10.startswith, endswith
  • 二、大小写转换
    • 1.lower,upper
    • 2.title
    • 3.captitalize
    • 4.swapcase
  • 三、查找与替换
    • 1.count
    • 2.index,rindex
    • 3.find
    • 4.replace
  • 四、去除类
    • 1.strip
    • 2.removeprefix, removesuffix
  • 五、分割与连接
    • 1.split,rsplit
    • 2.splitlines
    • 3.partition,rpartition
    • 4.join
  • 六、鸭子类型
    • 1.可迭代对象
    • 2.容器对象
    • 3.上下文管理器
    • 4.可调用对象
    • 5.文件类对象
    • 6.序列类型
    • 7.比较对象
  • 练习
    • 1.判断数字的奇偶
    • 2. 提取字母和数字
    • 3. 检查密码强度
    • 4. 猜数字游戏
    • 5.敏感词替换
    • 6.凯撒密码
    • 7.找出最长子串


前言

字符串是不可变对象

任何对字符串的修改操作(如替换、删除、拼接)都会返回新的字符串对象,而不是修改原字符串。

原字符串在内存中的值保持不变。

字符串的常用方法,字符串用得最多的类型之一

查看函数的帮助: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’]


一、字符串判断

1.isalpha

判断字符串是否完全由字母组成

  • string.isalpha()
print(msg.isalpha())		# True
print("你好".isalpha())      # True(中文也是字母)
print("hello".isalpha())	# False

2.isalnum

判断字符串是否完全由字母或数字字符组成

  • string.isalnum()
print("Hello".isalnum())  # True
print("12345".isalnum())  # True
print("1a".isalnum())	  # True
print(msg.isalnum())	  # Fasle(包含空格)

3.isdigit

判断字符串是否完全由数字组成,不仅检测 ASCII 数字(0-9),还包括其他 Unicode 数字字符(①②③),如罗马数字(VII)、上标数字 (2 3)等。

  • string.isdigit()
print("123".isdigit())      # True
print("一二三".isdigit())    # False

4.isnumeric

判断字符串是否完全由数值字符组成

  • string.isnumeric()

isnumeric() 支持以下字符:

  1. 十进制数字(如 0-9)

  2. Unicode 数字(如 ①②③、Ⅷ)

  3. 分数(如 ½、¾)

  4. 下标和上标数字(如 ²、₃)

  5. 罗马数字(如 Ⅰ、Ⅻ)

  6. 中文数字(一、二、三)

  7. 中文数字单位(如 十、百、千、万、亿)

    print("一二三零百千亿".isnumeric())	# True
    

5.isdecimal

判断字符串是否只包含十进制数字字符(0-9)

  • string.isdecimal()
print("12345".isdecimal())  # True
print("123a".isdecimal())   # False
print("-123".isdecimal())   # False

6.isspace

判断字符串是否只包含空白字符

  • string.isspace()

isspace()能识别以下 Unicode 空白字符:

  1. 空格 ’ '(ASCII 32)
  2. 制表符 ‘\t’(ASCII 9)
  3. 换行符 ‘\n’(ASCII 10)
  4. 回车符 ‘\r’(ASCII 13)
  5. 垂直制表符 ‘\v’ 或 ‘\x0b’(ASCII 11)
  6. 换页符 ‘\f’ 或 ‘\x0c’(ASCII 12)
  7. 其他 Unicode 空白字符(如不间断空格 ‘\xa0’、蒙古文元音分隔符等)
print("   ".isspace()) 	   # True
print("\t\n\r".isspace())  # True
print("  a  ".isspace())   # False
print("".isspace())		   # False

7.istitle

判断字符串是否符合标题格式
标题格式:字符串中每个单词的首字母都是大写,其余字母都是小写

  • string.istitle()
print("Hello World".istitle())  # True
print("Hello WORLD".istitle())  # False

8.isidentifier

判断字符串是否符合Python 标识符(变量名)的命名规则

  • string.isidentifier()
  • Python 标识符的命名规则
    首字符:必须是字母(大小写均可)或下划线 _
    后续字符:可以是字母、数字或下划线
    不能是:Python 的保留关键字(如 if、for、def 等)
print("VarName".isidentifier()) # True
print("123var".isidentifier())  # False
print("hello world".isidentifier())  # False(包含空格)
print("if".isidentifier())  # False(保留关键字)

9.islower,isupper

islower 判断字符串中的所有字母字符是否全为小写
isupper 判断字符串中的所有字母字符是否全为大写

  • string.islower()
  • string.isupper()
print("abc".isupper())		# True
print("aBc".islower())		# False
print("abc".isupper())		# False

10.startswith, endswith

startswith 判断字符串是否以特定前缀开头
endwith 判断字符串是否以特定后缀结尾

  • string.startswith(prefix[, start[, end]])
  • string.endswith(suffix[, start[, end]])
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

二、大小写转换

1.lower,upper

lower 将字符串中的所有字母转换为小写
upper 将字符串中的所有字母转换为大写

  • string.lower()
  • string.upper()
print("aBc".lower())	# abc
print("abC".upper())	# ABC

2.title

将字符串中每个单词的首字母转换为大写,其余字母转换为小写
任何非字母字符(如空格、数字、符号)被视为单词的分隔符

  • string.title()
print("aBc1中国".title())	  # Abc1中国
print("hElLo wOrLd".title())  # Hello World

3.captitalize

将字符串的首字母转换为大写,其余字母转换为小写

  • string.capitalize()
print("hElLo wOrLd".capitalize())  # Hello world
print("123aBc".capitalize())  	   # 123abc

4.swapcase

将字符串中的大写字母转为小写,小写字母转为大写,而其他字符保持不变(大小写互换)

  • string.swapcase()

    print("Hello World".swapcase())  # hELLO wORLD
    

三、查找与替换

1.count

用于统计序列中某个元素出现的次数

  • S.count(sub[, start[, end]]) -> int
    # [] => 可选项
    # <>/没有括号 => 必填项
    # -> => 返回值的类型
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

2.index,rindex

用于从左侧开始查找子串,并返回其首次出现的索引位置,索引从 0 开始。如果子串不存在,抛出 ValueError 异常

  • S.index(sub[, start[, end]]) -> int
  • rindex(),从右侧查找
print("hello".index("l")) 	  # 2
print("hello".index("l", 3))  # 3
print("banana".rindex("a"))   # 5

3.find

用于从左侧开始查找子串,并返回其首次出现的索引位置。如果子串不存在,则返回 -1

  • string.find(sub[, start[, end]])
print("hello".find("l"))  # 2
print("hello".find("x"))  # -1

4.replace

将字符串中的指定子串替换为新的字符串

  • string.replace(old, new[, count])
  • old:要替换的旧子串。
  • new:替换后的新子串。
  • count:最多替换次数,默认为 -1(替换所有匹配项)
print("Hello WOrld".replace("O", "o")) # Hello World
print("banana".replace("a", "X", 2))   # bXnXna

四、去除类

1.strip

用于去除字符串首尾的指定字符(默认移除空白字符)
string.strip([chars])

  • lstrip 去除左边
  • rstrip 去除右边
print(" Jack ".strip())		# Jack
print(".Jack ".lstrip(".")) # Jack 
print(" Jack#".rstrip("#")) #  Jack

2.removeprefix, removesuffix

去除字符串开头的指定前缀/后缀
必须完全匹配才会去除

  • string.removeprefix(prefix)
  • string.removesuffix(suffix)
print("unhappy".removeprefix("un"))	   # happy
print("unhappy".removesuffix("happy")) # un

五、分割与连接

1.split,rsplit

将字符串按指定分隔符分割成多个子字符串,并返回一个列表

  • string.split(sep=None, maxsplit=-1)
  • rsplit(sep=None, maxsplit=-1):从右侧开始分割
  • sep:分隔符,默认为所有空白字符(空格、制表符、换行符等)
  • maxsplit:最大分割次数,默认为 -1(不限制)
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']

2.splitlines

按行分割(处理 \n、\r、\r\n 等)

splitlines() 能识别以下换行符:

  1. \n(Unix/Linux 换行符)
  2. \r(旧 Mac 系统换行符)
  3. \r\n(Windows 换行符)
  4. \v 或 \x0b(垂直制表符)
  5. \f 或 \x0c(换页符)
  6. \x1c(文件分隔符)
  7. \x1d(组分隔符)
  8. \x1e(记录分隔符)
  9. \x85(下一行)
  10. \u2028(行分隔符)
  11. \u2029(段落分隔符)
  • string.splitlines([keepends])
  • keepends:布尔值,是否保留换行符。默认为 False(不保留)
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']

3.partition,rpartition

按指定分隔符将字符串分割为三部分,并返回一个元组

  • string.partition(sep)
  • rpartition(sep):从右侧开始分割(返回最后一个匹配的分隔符)
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')

4.join

将可迭代对象(如列表、元组)中的元素连接成一个字符串

  • separator.join(iterable)
  • separator:连接符字符串(如 “,”、“-”、“”)。
  • iterable:可迭代对象(如列表、元组、集合、字符串等)
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)是一种编程风格,它不关注对象的具体类型,而是关注对象是否实现了特定的方法或协议。

1.可迭代对象

是指可以被遍历(迭代)的对象
支持 for 循环和 iter()
字符串,列表,元组,字典,集合都是可迭代对象

方法
__iter__():返回一个迭代器(Iterator)对象。
__getitem__():支持通过整数索引访问元素(从 0 开始)

  • 循环遍历:for 循环自动将可迭代对象转换为迭代器
  • 解包操作:a, b = (1, 2)
  • 列表推导式:[x*2 for x in iterable]
  • 生成器表达式:(x*2 for x in iterable)
  • 内置函数:sum()、max()、min()、sorted() 等
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

2.容器对象

是一种可以包含其他对象的对象,它们实现了特定的方法来支持元素的存储、访问和管理

字符串、列表、集合都是容器

方法
__contains__(self, item):支持 in 操作符,检查元素是否存在
__len__(self):支持 len() 函数,返回容器长度

  • 成员检查:item in container
  • 长度计算:len(container)
  • 遍历:for item in container
# 判断子串
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

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

4.可调用对象

可以像函数一样被调用(使用 () 运算符)的对象或实体
函数、方法、类都是可调用对象

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

5.文件类对象

是一种实现了文件接口的对象,也称为类文件对象流对象这类对象支持文件的基本操作(如读取、写入、关闭),但不一定对应物理文件,可能是内存中的数据、网络连接或其他数据源

方法

  • read(size=-1):读取指定字节数(默认读取全部)。
  • write(data):写入数据并返回写入的字节数。
  • close():关闭对象并释放资源。
  • seek(offset[, whence]):移动文件指针位置。
  • tell():返回当前文件指针位置。
# 标准库中的 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

6.序列类型

是一种可迭代的容器,支持通过索引访问元素

  • 可变序列:列表 、字节数组
  • 不可变序列:字符串 、元组 、字节

通用操作

  • 索引访问:seq[index]
  • 切片:seq[start:stop:step]
  • 长度:len(seq)
  • 成员检查:x in seq
  • 重复:seq * n
  • 拼接:seq1 + seq2
  • 遍历:for x in seq
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]

7.比较对象

是指实现了比较运算符(如 <、>、== 等)的对象。通过实现这些方法,对象可以用于排序、最大 / 最小值查找、条件判断等操作

常用的比较方法有:

  • __lt__(self, other):小于(<)
  • __le__(self, other):小于等于(<=)
  • __eq__(self, other):等于(==)
  • __ne__(self, other):不等于(!=)
  • __gt__(self, other):大于(>)
  • __ge__(self, other):大于等于(>=)
# 列表、元组、字符串都可以用 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"(按年龄比较)

练习

1.判断数字的奇偶

number = input("请输入一个整数:")
if number.isdigit():
    if int(number) % 2 == 0:
        print(f"{number}是偶数")
    else:
        print(f"{number}是奇数")
else:
    print("请输入整数")

2. 提取字母和数字

从键盘接收一个字符串,将字符串的字母和数字提取出来

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

3. 检查密码强度

从键盘输入密码,检查密码强度,最高分5分,有1个不满足条件减1分,列出未满足条件的规则

  • 长度至少8位
  • 必须包含大写字母,小写字母,数字,特殊字符任意3种
  • 不能包含空格
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)

4. 猜数字游戏

  • 系统内生成一个数字,让用户来猜
  • 用户输入猜它的数字,系统告诉你打了或小了
  • 每个用户可以猜5次
  • 如果5次都没有猜出来,提醒用户:“机会已经用完,游戏结束!”
  • 中间猜出来了,提示“恭喜你猜对了!”
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("请输入一个数字")

5.敏感词替换

  • 接收用户输入的字符串,如果包含敏感词,需要将敏感词的部分替换成*
  • 如敏感词为abc,用户输入的字符串为hello world abcdefgabc => 替换为hello world ***defg***
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)    

6.凯撒密码

  • 实现简单的字母位移
  • 用户输入字符串及位移数量
  • 如“abAdef",位移3 => “deDghi”
msg = "abAdef"
msg_caesar_cipher = ''
for i in msg:
		# ord()返回单个字符的 Unicode 码点
        msg_caesar_cipher += chr(ord(i) + 3)
print(msg_caesar_cipher)

7.找出最长子串

  • 连续字符:找出字符串中最长的重复字符
  • 如aaabbbbb => bbbbb
# 定义最长连续子串的起始字符和长度
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}")

你可能感兴趣的:(Python,python,开发语言)