免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 16665 | 回复: 10
打印 上一主题 下一主题

如何用python把文件中每行字符前面的空格去掉? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-09-25 23:17 |只看该作者 |倒序浏览
比如有如下文件:
This is the fist line
    this is second line and with some space in the front
hi! I'm the 3rd line!

变成:
This is the fist line
this is second line and with some space in the front
hi! I'm the 3rd line!



谢谢!

论坛徽章:
0
2 [报告]
发表于 2005-09-26 00:00 |只看该作者

如何用python把文件中每行字符前面的空格去掉?

  1. >;>;>; f=open(r'd:\test.txt', 'r')
  2. >;>;>; while 1:
  3. ...         line = f.readline()
  4. ...         if not line: break
  5. ...         print line.strip()
  6. ...        
  7. This is the fist line
  8. this is second line and with some space in the front
  9. hi! I'm the 3rd line!
复制代码

论坛徽章:
0
3 [报告]
发表于 2005-09-26 09:28 |只看该作者

如何用python把文件中每行字符前面的空格去掉?

Yeah! Thanks a lot!

我原来还想着需要好多行语句才能解决,没想到利用一个字符串的方法就解决了!对于初学者来说,如果有一本中文版的参考手册,那该多好啊!

论坛徽章:
0
4 [报告]
发表于 2005-09-26 09:53 |只看该作者

如何用python把文件中每行字符前面的空格去掉?

你仔细找一下,已经有很多python中文化的东西了。

论坛徽章:
0
5 [报告]
发表于 2005-09-26 10:21 |只看该作者

如何用python把文件中每行字符前面的空格去掉?

这些东西还在于编程的经验,用得多了就熟了。因此需要对python的模块,内置的方法,类的方法要熟悉才行,需要自已多看。还有就是对于拿不准的或希望可以改进的地方拿出来讨论,然后再根据讨论结果进行有目的的学习在,比光在那里啃书要强得多。

论坛徽章:
0
6 [报告]
发表于 2009-01-08 14:03 |只看该作者
>>> for line in open('urfile', 'r'):
...     print line.lstrip(),
...
This is the fist line
this is second line and with some space in the front
hi! I'm the 3rd line!

论坛徽章:
0
7 [报告]
发表于 2009-01-08 14:51 |只看该作者

回复 #2 wolfg 的帖子

import re
r=open('file','r')
s=r.readlines()
r.close()
ss=''
for i in s:
ss+=re.sub('^\s*','',i)
print ss
这样行不行呀,我也刚学python
我写小一个小脚本,有空去看一看
http://yesorwong.appspot.com

论坛徽章:
0
8 [报告]
发表于 2009-01-08 14:56 |只看该作者
>>> [line.lstrip() for line in open("c:/response.txt")]

这个帖子也被翻出来了啊。。。

论坛徽章:
0
9 [报告]
发表于 2009-01-08 17:51 |只看该作者
今天学到一招。

论坛徽章:
0
10 [报告]
发表于 2009-01-09 10:42 |只看该作者
应该可以用reduce()来解决。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP