ribre817
ribre817

Reputation: 23

How to convert lines read from a file into one long string?

I am trying to create a postfix calculator. I have a file named expressions.txt that comes with six postfix operations. When I read the files in, it gives me a list with a bunch of new lines. For example,

f = open("expressions.txt", "r")
expression = f.readlines()

gives me:

['5 4 3 + 2 * -\n', '8 5 *\n', '20 5 /\n', '3 8 6 + *\n', '3 4 + 9 - 12 +\n', '9 3 2 1 + + /\n', '3 + 4\n', '* 3 4 5 + *\n', '4 9 1 3 + -\n', 'h 3 +\n']

I need

['5 4 3 + 2 * 8 5 * 20 5 / 3 8 6 ... ]

and so on and so on. I am trying to figure out how to instead of get each line into a list, i need each line to be joined into one big string.

EDIT: Okay, here is the full code.

from ArrayStack import *

evaluation = Stack()

def main():
   count = 0
   f = open("expressions.txt", "r")
   l = f.readlines()
   for char in l:
     char.replace("\n","")
     char.split(' ')
     evaluation.push(char)
   print(evaluation.data)

It is still not working to where I can push each number and operation onto the stack.

Upvotes: 0

Views: 8288

Answers (5)

f.rodrigues
f.rodrigues

Reputation: 3587

expression = ['5 4 3 + 2 * -\n', '8 5 *\n', '20 5 /\n', '3 8 6 + *\n', '3 4 + 9 - 12 +\n', '9 3 2 1 + + /\n', 
          '3 + 4\n',
        '* 3 4 5 + *\n', '4 9 1 3 + -\n', 'h 3 +\n']

expression = [''.join([char for char in ''.join(expression) if char != '\n'])]

Output:

["5 4 3 + 2 * -8 5 *20 5 /3 8 6 + *3 4 + 9 - 12 +9 3 2 1 + + /3 + 4* 3 4 5 + *4 9 1 3 + -h 3 +"]

Upvotes: 0

whereswalden
whereswalden

Reputation: 4959

If you can control the input file, this is easiest with tr on unix:

tr '\n' '' < input_file

If you have to use python, this will work:

with open('file') as f:
  expression = f.read().replace('\n', '')

Notice that I used f.read() instead of f.readlines(). f.read() returns a string rather than a list of strings, which saves you re-joining the lines later.

Upvotes: 2

James Mills
James Mills

Reputation: 19030

expressions = "".join(line.rstrip("\n") for line in open("expressions.txt", "r"))

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

>>> l = ['5 4 3 + 2 * -\n', '8 5 *\n', '20 5 /\n', '3 8 6 + *\n', '3 4 + 9 - 12 +\n', '9 3 2 1 + + /\n', '3 + 4\n', '* 3 4 5 + *\n', '4 9 1 3 + -\n', 'h 3 +\n']
>>> s ="".join(i.replace("\n","") for i in l)
'5 4 3 + 2 * -8 5 *20 5 /3 8 6 + *3 4 + 9 - 12 +9 3 2 1 + + /3 + 4* 3 4 5 + *4 9 1 3 + -h 3 +'

Also if you want to take it one step further to prepare for parsing (if that's what you're going for) you can do this

>>> s.replace(" ","")
'543+2*-85*205/386+*34+9-12+9321++/3+4*345+*4913+-h3+'

Upvotes: 1

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44092

Instead of replace, strip can serve you too:

with open("expressions.txt") as f:
    expression = "".join(line.strip("\n") for line in f)

Upvotes: -1

Related Questions