当前位置: 首页 > news >正文

Python中字符串常用的操作方法

在Python中,字符串是不可变序列类型,提供了丰富的内置方法。以下是常用的字符串操作方法及示例:

1. 大小写转换

  • lower() 转小写;

  • upper() 转大写;

  • capitalize() 首字母大写;

  • title() 每个单词首字母大写;

  • swapcase() 大小写互换 ;

print("HELLO".lower()) # hello
print("hello".upper())  # HELLO
print("python".capitalize())  # Python
print("hello world".title())  # Hello World
print("PyThon".swapcase())  # pYtHON

2. 查找与替换

  • find(sub, start, end):查找子串,返回索引,找不到返回-1,start 和 end 为可选参数;

  • rfind(sub):从右侧查找子串 ;

  • index(sub):类似find(),但找不到时会报错;

  • replace(old, new, count):替换子串,count指定替换次数为可选参数;
print("apple".find("p")) #1
print("apple".find("p",3)) # -1print("apple".rfind("p")) # 2
print("apple".index("p")) # 1 找不到报错
print("banana".replace("a", "o", 2)) # bonona

3. 字符串判断

  • startswith(prefix, start, end):是否以指定前缀开头,start 和 end 为可选参数;

  • endswith(suffix):是否以指定后缀结尾 ;

  • isalpha():是否全为字母

  • isdigit():是否全为数字 ;

  • isalnum():是否全为字母或数字 ;

  • isspace():是否全为空白符 ;

print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
print("123ABC".isdigit()) # False
print("123".isdigit()) # True
print("123ABC".isalnum()) # True
print("\t \n".isspace()) # True

4. 分割与连接

  • split(sep,maxsplit) :按分隔符分割为列表 ;

  • rsplit(sep,maxsplit): 从右侧分割字符;

  • splitlines():按行分割;

  • join(iterable):连接字符串序列;

print("a,b,c".split(",",1)) #['a', 'b,c']
print("a,b,c".rsplit(",",1)) #['a,b', 'c']
print("line1\nline2".splitlines()) # ['line1', 'line2']
print("!".join(["a", "b", "c"]) ) #a!b!c

5. 空白处理

  • strip():移除两侧空白或指定字符;

  • lstrip():移除左侧空白或指定字符;

  • rstrip():移除右侧空白或指定字符;

print("  hello  ".strip()) # hello
print("xxxworld".lstrip("xxx")) # world
print("helloxxx".rstrip("xxx")) # hello

6. 对齐与填充

  • center(width):居中填充 ; 

  • ljust(width):左对齐填充;

  • rjust(width):右对齐填充;

  • zfill(width):左侧用0填充;

print("center".center(8,'0')) # 0center0
print("hello".ljust(8,'0')) # hello000
print("hello".rjust(8,'0')) #000hello
print("hello".zfill(10)) #00000hello

7. 格式化

  • f 格式化字符串;

  • format() 格式化表达式;

name = "Alice"
print(f"Hello, {name}!") #Hello, Alice!
print("{0} + {1} = {2}".format(1, 2, 3)) #1 + 2 = 3

8. 其他操作

  • len(str):获取字符串长度;

  • in:检查字符串存在某个字符;

  • not in:检查字符串不存在某个字符;

  • count(sub,start,end):统计子串出现次数 ;

  • encode(encoding="utf-8"):编码为字节;

print(len("hello world")) # 11
print("a" in("apple")) # True
print("o" not in("apple")) #True
print("aaabbbccc".count("a",0,2)) #2
print("你好".encode(encoding="utf-8")) # b'\xe4\xbd\xa0\xe5\xa5\xbd'

掌握这些方法可高效处理文本数据,注意字符串不可变性:所有操作均返回新字符串,原字符串不变。

http://www.lryc.cn/news/573138.html

相关文章:

  • mysql导入大sql(比如10GB的sql文件)
  • 开源AI智能名片链动2+1模式S2B2C商城小程序:破解微商代理模式困局的数字化创新路径
  • MySQL存储引擎与架构
  • 在AI普及的大环境下神经网络在新能源汽车热管理系统中的应用简介
  • CLion开发Qt桌面程序_git的简单使用_小团体
  • opencv try-catch
  • day38-Django(4)
  • AI大模型学习之基础数学:高斯分布-AI大模型概率统计的基石
  • 自定义Django rest_framework中response的示例
  • 一个小BUG引发的对Mybatis-Plus的模糊查询的思考
  • 基于机器学习的侧信道分析(MLSCA)Python实现(带测试)
  • 从代码学习深度学习 - 预训练BERT PyTorch版
  • flutter环境变量记录
  • 为WIN10微软输入法的全角切换Bug禁用Shift+Space组合键
  • 软件工程概述知识点总结
  • (LeetCode ) 169. 多数元素(哈希表 || 二分查找)
  • python学智能算法(十五)|机器学习朴素贝叶斯方法进阶-CountVectorizer多文本处理
  • C++链表的虚拟头节点
  • Wire--编译时依赖注入工具
  • Java面试题025:一文深入了解数据库Redis(1)
  • 4.1 FFmpeg编译选项配置
  • 缓存与加速技术实践-Kafka消息队列
  • ARCGIS国土超级工具集1.6更新说明
  • 【RAG优化】深度解析开源项目MinerU:从PDF解析到多模态理解的工业级解决方案
  • Linux - 安装 git(sudo apt-get)
  • PostgreSQL/Hologres 外部服务器系统表 pg_foreign_server 详解
  • 基于 Flutter+Sqllite 实现大学个人课表助手 APP(期末作业)
  • 什么是RoCE网络技术
  • 飞书使用技巧 --- 飞书批量导入建群 (以导入名单的方式)
  • HTML5简介