如何从Python中的readline()中删除/ n?

时间:2013-04-27 02:25:38

标签: python list readline

    a = open('expressoes.txt', 'r')
i = 0
j = 0
pilhaop = []
string = []

b = a.readlines()
while j in range(len(b)):
        fixa = b[j]
        print b[j]
        while i < len(fixa):
                if fixa[i] == '^':
                        pilhaop.append(fixa[i])
                elif fixa[i] == '*' or fixa[i] == '/' or fixa[i] == '%':
                        if len(pilhaop)>0 and pilhaop[-1] in '^':
                                string.append(pilhaop.pop())
                        else:
                                pilhaop.append(fixa[i])
                elif fixa[i] == '+' or fixa[i] == '-':
                        if len(pilhaop)>0 and pilhaop[-1] in '* / %':
                                string.append(pilhaop.pop())

                        pilhaop.append(fixa[i])
                else: #se for digito passa direto para posfixa
                        string.append(fixa[i])

                i += 1

        #esvazia a pilha
        while len(pilhaop)>0:
                string.append(pilhaop.pop())
        print ''.join(string)
        print "........................"

        j += 1

我有这个代码,我正在尝试将中缀表达式(5 + 3 * 2)从txt文件转换为后缀表达式(532 * +)。代码正在做正确的事情,但是当我在txt文件上有多个表达式时,它会像这样:

on txt file:

5+3*2
6*4+8
跑完后

5+3*2

532
*+
........................
6*4+8
532
*+
........................

当我打印'string'而没有加入时,它显示:['5','3','2','/ n','*','+']

你能帮帮我吗?

2 个答案:

答案 0 :(得分:3)

使用strip功能删除换行符

fixa = b[j].strip()

答案 1 :(得分:0)

我用这个。在我看来,它稍微耗费一些时间(O(1)vs O(n)),因为你不需要检查你的字符串中的每个字符只是剪掉最后一个字符。

以下是代码:

with open('expressoes.txt', 'r') as a:
    line = a.readline()[:-1]

在你的情况下是:

b = a.readlines()
while j in range(len(b)):
    fixa = b[j][:-1]