博客
关于我
【笔记】Python3中使用string模块删除&替换字符串中的特定值
阅读量:573 次
发布时间:2019-03-09

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

官方文档

static str.maketrans(x[, y[, z]])
This static method returns a translation table usable for str.translate().
If there is only one argument,
it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.
If there are two arguments,
they must be strings of equal length,
and in the resulting dictionary,
each character in x will be mapped to the character at the same position in y.
If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

语法

i.translate(str.maketrans(x, y, z)

参数

  • x–>在字符串中所需识别(匹配)的值
  • y–>将要填入到所匹配值的位置的新值。新值的长度需与原值相等。

x、y为配套使用,需同时存在可以为空

  • z–>需要删除的值

示例

import stringi = 'iiiiiloveyou'i.translate(str.maketrans('','','i')print(i)'loveyou'---i.translate(str.maketrans('i','y')print(i)'yyyyyloveyou'

与split()区别

如果将子字符串比喻为火车的一节节车厢。

split()对字符串的处理可以理解为:将一节节车厢之间的链接环拿走,各个车厢变成一个个单独的个体,而非一个整体,也就是为什么输出不是一个字符串,而是一个列表的原因。

string模块则是将车厢之间的链接环先断开,再将需要的车厢重现链接成为一辆火车,而不是单独的个体。因此输出结果为一个字符串。

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

你可能感兴趣的文章
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>
mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
查看>>
MYSQL 查看最大连接数和修改最大连接数
查看>>
MySQL 查看有哪些表
查看>>
mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
查看>>
MySql 查询以逗号分隔的字符串的方法(正则)
查看>>
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
查看>>
mysql 查询数据库所有表的字段信息
查看>>
【Java基础】什么是面向对象?
查看>>
mysql 查询,正数降序排序,负数升序排序
查看>>
MySQL 树形结构 根据指定节点 获取其下属的所有子节点(包含路径上的枝干节点和叶子节点)...
查看>>
mysql 死锁 Deadlock found when trying to get lock; try restarting transaction
查看>>
mysql 死锁(先delete 后insert)日志分析
查看>>
MySQL 死锁了,怎么办?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 添加列,修改列,删除列
查看>>
mysql 添加索引
查看>>