一、对于字符串特殊字符的替换

对于字符串内,\n的处理,如何去掉

s='123,456\n'
s1=s.strip('\n')
s2=s.replace('\n','')
print(s)
print(s1)
print(s2)

执行结果

123,456

123,456
123,456

strip(),能去除字符串首尾的特殊字符;而replace没有此限制

strip()的官方解释:strip()默认去除的是首尾的空白字符;如果给定的话,去除给定的字符;

    def strip(self, *args, **kwargs): # real signature unknown
"""
Return a copy of the string with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
"""

replace()的官方解释:默认用新值替换所有的出现的字符;如果给定数量,则按数量进行替换

"""
Return a copy with all occurrences of substring old replaced by new. count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences. If the optional argument count is given, only the first count occurrences are
replaced.
"""

如:

s='123a,a456a'

#把字符串中的字符 a 替换为字符b,只替换前2个
s3=s.replace('a','b',2)
#把字符串中的字符 a 都替换为字符b,
s4=s.replace('a','b')
print(s)
print(s3)
print(s4)

执行结果:

123a,a456a
123b,b456a
123b,b456b

 二、对于文件读取后,内容的替换

如,有个文件,text,内容如下:

1234
4567
this
ok

python的处理方法可以这样处理,代码如下:

data_list=[i.replace('\n','') for i in data_list];用了字符串的replace函数及列表推导式
with open('text') as f:
data_list=f.readlines()
data_list=[i.replace('\n','') for i in data_list]
print(data_list)

执行结果:

['1234', '4567', 'this', 'ok']

最新文章

  1. Java工作环境笔记
  2. 在centos6.7用yum安装redis解决办法
  3. C++面试中关于sizeof问题总结
  4. MySQL性能优化经验
  5. php+phpquery简易爬虫抓取京东商品分类
  6. (leetcode)Implement Stack using Queues
  7. MySQL行列转换
  8. UVa 10806 Dijkstra,Dijkstra(最小费用最大流)
  9. Nintex Workflow Get Attachment link
  10. Confluence 6 附件存储选项
  11. (并发编程)进程IPC,生产者消费者模型,守护进程补充
  12. Property attributes
  13. 【SPL标准库专题(3)】 Classes
  14. 开发人员如何正确对待BUG?
  15. hdu1238 Substrings (暴力)
  16. linux sar命令详细说明相关参数
  17. 初见-TensorRT简介<转>
  18. OpenCV iOS开发(一)——安装(转)
  19. Qt5连接Mysql环境配置
  20. 【转】JMeter中对于Json数据的处理方法

热门文章

  1. voxel体素网络滤波器
  2. 如何将项目打包成apk或exe程序
  3. 精华推荐 |【算法数据结构专题】「延时队列算法」史上非常详细分析和介绍如何通过时间轮(TimingWheel)实现延时队列的原理指南
  4. Linux:touch 修改文件的时间
  5. K8S 实用工具之一 - 如何合并多个 kubeconfig?
  6. c++_成员函数回调
  7. Java学习笔记(二)java流程控制
  8. CF1738E Balance Addicts
  9. Hanlp 在Python环境中安装、介绍及使用
  10. c++ class派生与多态