下面是python块代码,
def compute_hcf(x, y):
while(y):
x, y = y, x % y
return x
我想将其转换为如下所示的单行,
def compute_hcf(x, y):\n\t while(y): \n\t\t x, y = y, x % y \n\t return x
我有以下方法来解决这个问题,
def convert(fname):
newLines = ''
with open(fname, 'r') as f:
for line in f:
num_spaces = 0
for letter in line:
if letter != ' ':
break
num_spaces += 1
if num_spaces == 3:
line = line.replace(' '*3, '\\t') #If number of Spaces is 3, replace with a single tab
elif num_spaces == 4:
line = line.replace(' '*4, '\\t') #If number of Spaces is 4, replace with a single tab
elif num_spaces == 7:
line = line.replace(' ' *7, '\\t\\t') #If number of Spaces is 7, replace with double tab
elif num_spaces == 8:
line = line.replace(' ' * 8, '\\t\\t') #If number of Spaces is 8, replace with double tab
line = line + '\\n' #Adding new line at the end of the line
newLines = newLines + line
converted = ''.join(newLines)
print(converted)
convert('fileWithInputContent.txt')
实际输出:
def compute_hcf(x, y):
\n\twhile(y):
\n\t\tx, y = y, x % y
\n\treturn x\n
预期输出:
def compute_hcf(x, y):\n\t while(y): \n\t\t x, y = y, x % y \n\t return x