初学python多次,都被python的缩进搞得头疼,还是习惯c的风格,查了查好像没人弄一个c风格的python,只能自己想办法了。
解决办法很简单,就是给程序块加上大括号,方式如下:
#!/usr/bin/python
#coding:utf-8
import string
infilename = raw_input('enter file name:')
index = infilename.find('.pyi')
if index != -1:
{
outfilename = infilename[:index]
outfilename += '.py'
}
else:
{
print 'Wrong file type!'
exit()
}
count = 0
#with open(infilename,'r') as fin
#with open(outfilename,'w') as fout
fin = open(infilename,'r')
fout=open(outfilename,'w')
for line in fin.readlines():
{
line = line.strip()
if line.startswith('{'):
{
count += 1
continue
}
elif line.startswith('}'):
{
count -= 1
if count < 0:
{
print 'find a unmatch }'
exit()
}
continue
}
else:
{
x=count
print x
space = ''
while x > 0:
{
space += ' '
x -= 1
}
fout.write(space + line + '\n')
}
}
if count > 0:
{
print 'find a unmatch {'
}
fin.close()
fout.close()
下面是python原来的格式代码:
#!/usr/bin/python
#coding:utf-8
import string
infilename = raw_input('enter file name:')
index = infilename.find('.pyi')
if index != -1:
outfilename = infilename[:index]
outfilename += '.py'
else:
print 'Wrong file type!'
exit()
count = 0
#with open(infilename,'r') as fin
#with open(outfilename,'w') as fout
fin = open(infilename,'r')
fout=open(outfilename,'w')
for line in fin.readlines():
line = line.strip()
if line.startswith('{'):
count += 1
continue
elif line.startswith('}'):
count -= 1
if count < 0:
print 'find a unmatch }'
exit()
continue
else:
x=count
space = ''
while x > 0:
space += ' '
x -= 1
fout.write(space + line + '\n')
if count > 0:
print 'find a unmatch {'
fin.close()
fout.close()
为了区别,把加括号的代码扩展名定为".pyi"。运行上面第二个代码,输入第一个代码文件名(以".pyi"为扩展名),执行成功后会生成同名的扩展名为".py"的文件,代码符合python缩进要求。
这样再也不用发愁缩进的问题了。