不用缩进的python

初学者因Python的缩进规则感到困扰,本文介绍了一种使用大括号来替代缩进的方法,通过编写脚本将C风格的.pyi文件转换为符合Python缩进规范的.py文件,从而简化代码格式。

    初学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缩进要求。

    这样再也不用发愁缩进的问题了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值