python的縮排問題

在python3之後
tab跟4個空格不能混用了
pep-8說要用4個空格,但一直打4個空格實在是太麻煩了
所以寫了個可以把所有tab變成4個空格、以及所有4個空格變成tab的小程式
很好用喔哈哈

程式碼短短的
直接拿去用吧
import sys

def tab2fourSpaces(string):
 result_str = ''
 for char in string:
  if char=='\t':
   result_str += '    '
  else:
   result_str += char
 return result_str

def fourSpaces2tab(string):
 result_str = ''
 space_count = 0
 for char in string:
  if char == ' ':
   space_count += 1
   if space_count == 4:
    result_str += '\t'
    space_count = 0
  else:
   if space_count > 0:
    for i in range(space_count):
     result_str += ' '
    result_str += char
    space_count = 0
   else:
    result_str += char
    space_count = 0
 return result_str

def main():
 if sys.argv[2] == '1':
  new_content = []
  with open(sys.argv[1],'r') as fin:
   for input_line in fin:
    output_line = tab2fourSpaces(input_line) #already contain '\n'
    new_content.append(output_line)
  with open(sys.argv[1],'w') as fout:
   for line in new_content:
    fout.write(line)
 if sys.argv[2] == '2':
  new_content = []
  with open(sys.argv[1],'r') as fin:
   for input_line in fin:
    output_line = fourSpaces2tab(input_line)
    new_content.append(output_line)
  with open(sys.argv[1],'w') as fout:
   for line in new_content:
    fout.write(line)
if __name__ == '__main__':
 main()

就這樣

好了,今天的筆記到此結束
希望有幫助未來遺忘這些的自己,以及需要的人

留言

這個網誌中的熱門文章