python - 如何删除字符串的初始空格?
问题描述
我尝试读取一个文件,然后生成一个恒温的新文件。
我尝试阅读的文件中的示例。
0.000000 353.132629
10.000000 348.849274
20.000000 345.484161
30.000000 340.822479
40.000000 340.704346
50.000000 344.139404
60.000000 344.501953
70.000000 344.187286
80.000000 348.505554
90.000000 346.961700
然后我尝试生成的新文件
0.000000 343
10.000000 343
20.000000 343
30.000000 343
40.000000 343
50.000000 343
60.000000 343
70.000000 343
80.000000 343
90.000000 343
我无法解决的问题是如何只从我读取的文件中删除第一个空格。
在我的代码中,我将数字数据分成两列,但是因为程序获得了起始空间ValueError
。那么如何改进我的代码并摆脱我的问题呢?
我的python代码:
import sys
import os
import getopt
#function for replacing volumes over temperatures
def convert_to_volume_file(inputfile, outputfile, volume):
try:
file1 = open(inputfile, "r") #read input file
file2 = open(outputfile, "w+") #write new file for output
line = file1.readline()
while line != "":
if line[0] == '#':
file2.write(line)
elif line[0] == '@' and line[2] == 's':
file2.write('@ s0 legend "Volume"\n') #replace 'legend' for volume
elif line[0] == '@':
file2.write(line)
else:
line.replace(" ", "")
num = line.split(" ") #split data to 2 columns
num[1] = volume #overwriting volume to appropriate place
file2.write("%.6f %.4f\n"%(float(num[0]), float(num[1])))
line = file1.readline()
file1.close()
file2.close()
except OSError:
print("ERROR")
#main function that reads user inputs from command line
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"f:o:v:")
except getopt.GetoptError:
print("INPUT ERROR!!! Input form: -f <inputfile> -o <outputfile> -v <volume>")
return
for opt, arg in opts:
if opt in ("-f"): #input
inputfile = arg
elif opt in ("-o"): #output
outputfile = arg
elif opt in ("-v"): #volume of simulation box
volume = float(arg)
convert_to_volume_file(inputfile, outputfile, volume)
main(sys.argv[1:])
解决方案
您可以使用strip
、lstrip
和rstrip
方法分别从字符串的两端、左侧和右侧删除尾随空格。
line = line.strip() #removes trailing spaces from both ends of the string
line = line.lstrip() #removes trailing spaces from the left end of the string
line = line.rstrip() #removes trailing spaces from the right end of the string
我希望我已经过度简化了:)
推荐阅读
- android - java.lang.NoClassDefFoundError 与 Kotlin 数据类
- vb.net - 显示新表单时的视觉基本问题
- azure - 如何通过terraform将本地文件复制到azure vm?
- c++ - 3d 三角形卡住了 c++ opengl glfw
- flutter - 如何为给定类型的 Flutter 小部件强制执行某些参数值?
- javascript - 如何将参数注入 TestCafé 测试?
- authorization - 微服务中的授权 - 用户可以访问的行列表
- sql - SQL Server:为临时表创建聚集索引
- python - 计算器的功率增加字符串
- php - 如何为数据库查询返回给我的每一行制作饼图?