博客
关于我
Python - 字符串常用函数详解
阅读量:453 次
发布时间:2019-03-06

本文共 4007 字,大约阅读时间需要 13 分钟。

Python 字符串操作函数详解

本文将逐一分析 Python 中常用的字符串操作函数,帮助开发者更高效地处理字符串数据。

1. str.index(sub, start=None, end=None)

作用:查看子字符串 sub 是否存在于当前字符串中。如果存在则返回其第一次出现的索引位置;若不存在则抛出 ValueError 错误。

特点

  • 只会返回第一次匹配的索引位置。
  • 如果 startend 范围限制内不存在子字符串,会抛出错误。
  • 如果没有指定 startend,则默认从字符串开头开始搜索,直到末尾。

示例

str = "helloworldhhh"print(str.index("h"))  # 输出: 0print(str.index("hhh"))  # 输出: 7# print(str.index("test"))  # 输出: 直接报语法错误:ValueError: substring not found

执行结果

010

2. str.find(sub, start=None, end=None)

作用:与 index() 函数类似,用于查找子字符串 sub 在当前字符串中的位置。与 index() 有别的是,如果找不到子字符串,find() 会返回 -1,而不会抛出错误。

特点

  • 返回匹配结果的索引位置,-1 表示未找到。
  • 如果指定了 startend 范围,同样会在该范围内查找。

示例

str = "helloworldhhh"print(str.find("h"))  # 输出: 0print(str.find("hhh"))  # 输出: 7print(str.find("test"))  # 输出: -1

执行结果

010-1

3. str.count(sub, start=None, end=None)

作用:统计字符串中子字符串 sub 的出现次数。可以指定统计的范围 [start, end),左闭区间右开区间。

特点

  • 如果不指定 startend,则默认统计整个字符串。
  • 如果子字符串在指定范围内出现多次,每次统计都会增加计数。
  • 如果子字符串不在范围内出现,则返回 0

示例

str = "hello world !!! hhh"print(str.count(" "))  # 输出: 5print(str.count(" ", 5, 10))  # 输出: 1

执行结果

31

4. str.split(str="", num=string.count(str))

作用:将字符串按指定的 str 分割成列表。如果未指定 str,则默认按空字符串分割,这会将每个字符单独分割成一个子列表。

特点

  • num 参数决定了最多分割成 num + 1 个子字符串。
  • 如果 num 未指定,默认值为 string.count(str), 即字符串中 str 的出现次数。

示例

str = "hello world !!! hhh"print(str.split(" "))  # 输出: ['hello', 'world', '!!!', 'hhh']print(str.split(" ", 1))  # 输出: ['hello', 'world !!! hhh']

执行结果

['hello', 'world', '!!!', 'hhh']['hello', 'world !!! hhh']

5. str.strip(chars=" ")

作用:移除字符串的头尾指定字符序列 chars 中的字符,默认为空格。

特点

  • 移除的字符必须是连续的,且不能跨越空格或其他非空字符。
  • 如果 chars 中包含多个字符,可以同时移除多个字符。

示例

str = "   hello  every  "print("1", str.strip(), "1")  # 输出: "1 hello  every  1"print(str.lstrip())  # 输出: "hello  every  "print("1", str.rstrip())  # 输出: "1 hello  every  "str = "!!! cool !!!"print(str.strip("!"))  # 输出: "cool"

执行结果

1 hello  every  1hello  every  1 hello  every  cool

6. str.replace(old, new, count=-1)

作用:将字符串中的旧字符串 old 替换为新字符串 newcount 参数指定了最多替换次数,默认为 -1(表示替换所有可用的旧字符串)。

特点

  • 如果 count 为正数,只会替换该次数内的旧字符串。
  • 替换时不会影响其他部分的字符串。

示例

str = "hello world !!! hhh"print(str.replace(" ", "-"))  # 输出: "hello-world-!!!-hhh"print(str.replace(" ", "-", 1))  # 输出: "hello-world !!! hhh"

执行结果

hello-world-!!!-hhhhello-world !!! hhh

7. str.join(sequence)

作用:将输入序列中的元素用指定字符连接生成新的字符串。

特点

  • 适用于列表、元组等序列类型。
  • 元素必须是字符串,否则会报错。
  • 如果序列为空,返回空字符串。

示例

lists = ["1", "2", "3"]tuples = ("1", "2", "3")print("".join(lists))  # 输出: "123"print("".join(tuples))  # 输出: "123"print("-".join(lists))  # 输出: "1-2-3"

执行结果

1231231-2-3

8. 字符串大小写转换方法

方法

  • str.upper():将字符串转换为大写字母。
  • str.lower():将字符串转换为小写字母。

示例

str = "hello world !!! hhh"print(str.upper())  # 输出: "HELLO WORLD !!! HHH"print(str.lower())  # 输出: "hello world !!! hhh"

执行结果

HELLO WORLD !!! HHHhello world !!! hhh

9. 字符串前后缀检查方法

方法

  • str.startswith(prefix, start=None, end=None)

    作用:检查字符串是否以指定子字符串 prefix 开头。可以指定 startend 范围。

示例

str = "hello world !!! hhh"print(str.startswith("h"))  # 输出: Trueprint(str.startswith("hh"))  # 输出: Falseprint(str.startswith("h", 0, 5))  # 输出: True

执行结果

TrueFalseTrue

方法

  • str.endswith(self, suffix, start=None, end=None)

    作用:检查字符串是否以指定子字符串 suffix 结尾。可以指定 startend 范围。

示例

str = "hello world !!! hhh"print(str.endswith("h"))  # 输出: Trueprint(str.endswith("hhhh"))  # 输出: Falseprint(str.endswith("h", 7, 10))  # 输出: True

执行结果

TrueFalseTrue

10. 字符串验证方法

方法

  • str.isdigit()

    作用:检查字符串是否只由数字组成。

示例

str = "123134123"print(str.isdigit())  # 输出: True

执行结果

true

方法

  • str.isalpha()

    作用:检查字符串是否只由字母组成。

示例

str = "abc"print(str.isalpha())  # 输出: True

执行结果

true

11. 字符串格式化与分割

方法

  • str.splitlines([keepends])

    作用:将字符串按行分割。默认分割 \r, \r\n, 和 \n 三种换行符。如果指定 keepends,则保留换行符。

示例

str = "123456789"print(str.splitlines())  # 输出: ['', '123', '456', '789']with open("./file1.txt", encoding="utf-8") as f:    lists = f.read().splitlines()    print(lists)

执行结果

['', '123', '456', '789']['name: Jack   ;    salary:  12000', ' name :Mike ; salary:  12300', 'name: Luk ;   salary:  10030', '  name :Tim ;  salary:   9000', 'name: John ;    salary:  12000', 'name: Lisa ;    salary:   11000']

转载地址:http://cvkfz.baihongyu.com/

你可能感兴趣的文章
MySQL集群解决方案(4):负载均衡
查看>>
MySQL高级-视图
查看>>
nacos集群搭建
查看>>
Nessus漏洞扫描教程之配置Nessus
查看>>
Nest.js 6.0.0 正式版发布,基于 TypeScript 的 Node.js 框架
查看>>
Netpas:不一样的SD-WAN+ 保障网络通讯品质
查看>>
Netty WebSocket客户端
查看>>
Netty工作笔记0011---Channel应用案例2
查看>>
Netty工作笔记0014---Buffer类型化和只读
查看>>
Netty工作笔记0050---Netty核心模块1
查看>>
Netty工作笔记0084---通过自定义协议解决粘包拆包问题2
查看>>
Netty常见组件二
查看>>
netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
查看>>
Netty核心模块组件
查看>>
Netty框架的服务端开发中创建EventLoopGroup对象时线程数量源码解析
查看>>
Netty源码—2.Reactor线程模型一
查看>>
Netty源码—4.客户端接入流程一
查看>>
Netty源码—4.客户端接入流程二
查看>>
Netty源码—5.Pipeline和Handler一
查看>>
Netty源码—6.ByteBuf原理二
查看>>