删除python中的空白

2024-09-28 21:11:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python从SAC读取标题,但是在删除空白时遇到了问题。我想删除下一个电台名称前的空格,例如RPZ、TOZ、URZ。这是我的密码:

for s in stations:
    tr=st[0]
    h=tr.stats
    stnm = h.station
    tt = h.sac.t1

    print>>f,stnm, 'P', '1', tt,

我希望输出如下所示:

DSZ P 1 53.59RPZ P 1 72.80TOZ P 1 40.25URZ P 1 32.26 

然后转到32.26之后的新行。这就是我在tt后面加逗号的原因。你知道吗

但是,它当前的输出是这样的,在RPZTOZURZ之前有不需要的空格:

DSZ P 1 53.59 RPZ P 1 72.80 TOZ P 1 40.25 URZ P 1 32.26

有什么建议吗?我试过x.strip(),但我得到了答案

AttributeError: 'list' object has no attribute 'strip'.

Tags: 名称密码标题tr空白电台strip空格
2条回答

print语句正在添加空格;如果希望删除空格,请不要使用print,而是使用f.write()

f.write('{} P 1 {}'.format(stnm, tt))

这将使用带^{}的字符串格式来创建相同的输出格式,但是现在不会在tt值后面写入空格。你知道吗

作为Martin答案的替代方法,您还可以(对于python2.6+导入和)使用print函数,比如

# import only needed for Python2
from __future__ import print_function      

print(stnm, 'P', '1', tt, end='', file=f)

相关问题 更多 >