字符串内特殊字符的替换处理,如对\n的替换
2024-09-06 21:17:55
一、对于字符串特殊字符的替换
对于字符串内,\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']
最新文章
- Java工作环境笔记
- 在centos6.7用yum安装redis解决办法
- C++面试中关于sizeof问题总结
- MySQL性能优化经验
- php+phpquery简易爬虫抓取京东商品分类
- (leetcode)Implement Stack using Queues
- MySQL行列转换
- UVa 10806 Dijkstra,Dijkstra(最小费用最大流)
- Nintex Workflow Get Attachment link
- Confluence 6 附件存储选项
- (并发编程)进程IPC,生产者消费者模型,守护进程补充
- Property attributes
- 【SPL标准库专题(3)】 Classes
- 开发人员如何正确对待BUG?
- hdu1238 Substrings (暴力)
- linux sar命令详细说明相关参数
- 初见-TensorRT简介<;转>;
- OpenCV iOS开发(一)——安装(转)
- Qt5连接Mysql环境配置
- 【转】JMeter中对于Json数据的处理方法