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

python删除文件指定字符串,从Python中的字符串中删除特定字符

I'm trying to remove specific characters from a string using Python. This is the code I'm using right now. Unfortunately it appears to do nothing to the string.

for char in line:

if char in " ?.!/;:":

line.replace(char,'')

How do I do this properly?

解决方案

Strings in Python are immutable (can't be changed). Because of this, the effect of line.replace(...) is just to create a new string, rather than changing the old one. You need to rebind (assign) it to line in order to have that variable take the new value, with those characters removed.

Also, the way you are doing it is going to be kind of slow, relatively. It's also likely to be a bit confusing to experienced pythonators, who will see a doubly-nested structure and think for a moment that something more complicated is going on.

Starting in Python 2.6 and newer Python 2.x versions *, you can instead use str.translate, (but read on for Python 3 differences):

line = line.translate(None, '!@#$')

or regular expression replacement with re.sub

import re

line = re.sub('[!@#$]', '', line)

The characters enclosed in brackets constitute a character class. Any characters in line which are in that class are replaced with the second parameter to sub: an empty string.

In Python 3, strings are Unicode. You'll have to translate a little differently. kevpie mentions this in a comment on one of the answers, and it's noted in the documentation for str.translate.

When calling the translate method of a Unicode string, you cannot pass the second parameter that we used above. You also can't pass None as the first parameter. Instead, you pass a translation table (usually a dictionary) as the only parameter. This table maps the ordinal values of characters (i.e. the result of calling ord on them) to the ordinal values of the characters which should replace them, or—usefully to us—None to indicate that they should be deleted.

So to do the above dance with a Unicode string you would call something like

translation_table = dict.fromkeys(map(ord, '!@#$'), None)

unicode_line = unicode_line.translate(translation_table)

Here dict.fromkeys and map are used to succinctly generate a dictionary containing

{ord('!'): None, ord('@'): None, ...}

Even simpler, as another answer puts it, create the translation table in place:

unicode_line = unicode_line.translate({ord(c): None for c in '!@#$'})

Or create the same translation table with str.maketrans:

unicode_line = unicode_line.translate(str.maketrans('', '', '!@#$'))

* for compatibility with earlier Pythons, you can create a "null" translation table to pass in place of None:

import string

line = line.translate(string.maketrans('', ''), '!@#$')

Here string.maketrans is used to create a translation table, which is just a string containing the characters with ordinal values 0 to 255.

相关文章:

  • python基础读后感_《python基础教程 》第一章 读书笔记
  • 二叉树的字符图形显示程序_(CSPJ)入门级C++语言试题A卷答案解析阅读程序
  • 服务器显示地址正在使用_用Windows Storage Server 2008做iSCSI存储服务器
  • 权限设计表结构超详细_超详细!!五金模具组件及工程结构设计
  • flex 下对齐_开启 flex 与 grid 布局方式之旅
  • python中的and or的区别_Python 中 (,|)和(and,or)之间的区别
  • python csv模块dictwrite_Pythoncsv.DictWriterwriterow()返回
  • dataset__getitem___PyTorch 之Dataset和DataLoader
  • java 读取txt内容_不用怀疑!这就是把Java.I/O流讲解的最清楚的一篇文章
  • 表单所有input框置灰_别再对 Angular 表单的 ControlValueAccessor 感到迷惑
  • 要求的函数不受支持_支持向量机:如何对不可分数据进行分类?
  • java 内存泄漏_Java应用程序中的内存泄漏及内存管理
  • python制作网页样式_HTML基础做出属于自己的完美网页
  • using在sql中是什么意思_知否 | “开到荼蘼”的“荼蘼”是什么东西?
  • python如何导入数据库生成图表_python数据库操作常用功能使用详解(创建表/插入数据/获取数据)...
  • 8年软件测试工程师感悟——写给还在迷茫中的朋友
  • Android优雅地处理按钮重复点击
  • Apache Spark Streaming 使用实例
  • create-react-app做的留言板
  • crontab执行失败的多种原因
  • dva中组件的懒加载
  • JavaScript 基本功--面试宝典
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • magento2项目上线注意事项
  • Perseus-BERT——业内性能极致优化的BERT训练方案
  • SegmentFault 技术周刊 Vol.27 - Git 学习宝典:程序员走江湖必备
  • vue脚手架vue-cli
  • 闭包,sync使用细节
  • 力扣(LeetCode)56
  • 买一台 iPhone X,还是创建一家未来的独角兽?
  • 免费小说阅读小程序
  • 算法---两个栈实现一个队列
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 长三角G60科创走廊智能驾驶产业联盟揭牌成立,近80家企业助力智能驾驶行业发展 ...
  • ​草莓熊python turtle绘图代码(玫瑰花版)附源代码
  • #git 撤消对文件的更改
  • #鸿蒙生态创新中心#揭幕仪式在深圳湾科技生态园举行
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (11)MSP430F5529 定时器B
  • (function(){})()的分步解析
  • (Python第六天)文件处理
  • (十二)devops持续集成开发——jenkins的全局工具配置之sonar qube环境安装及配置
  • (转)LINQ之路
  • (转)scrum常见工具列表
  • (转)详解PHP处理密码的几种方式
  • .Net 6.0 处理跨域的方式
  • .NET Conf 2023 回顾 – 庆祝社区、创新和 .NET 8 的发布
  • .Net6 Api Swagger配置
  • .net6解除文件上传限制。Multipart body length limit 16384 exceeded
  • @vue/cli脚手架
  • [ CTF ] WriteUp- 2022年第三届“网鼎杯”网络安全大赛(朱雀组)
  • [ 攻防演练演示篇 ] 利用通达OA 文件上传漏洞上传webshell获取主机权限
  • [ACM] hdu 1201 18岁生日
  • [C# WPF] DataGrid选中行或选中单元格的背景和字体颜色修改
  • [CF407E]k-d-sequence