简体   繁体   中英

How to remove /n from readline() in Python?

    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

I have this code and I'm trying to convert infix expressions (5+3*2) from a txt file to postfix expressions (532*+). The code is doing the right thing, but when I have more than one expression on the txt file it goes like this:

on txt file:

5+3*2
6*4+8

after running:

5+3*2

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

When I print 'string' without joining, it shows: ['5','3','2','/n','*','+']

Could you help me?

使用strip函数删除换行符

fixa = b[j].strip()

I use this. In my opinion it is slightly less time-consuming (O(1) vs O(n)) because you don't need to check every single char in your string just cut the last one.

Here is the code:

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

In your case it is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM