0

I asked a question about this earlier but noone could answer me - I have this code and want what is defined as e to be written into a new ASCII file in one line. I was suggested to use the tuple function which didn't work since it only takes on argument but I have two (a and b). So now I just tried the join function. The code is below

we=open('new.txt','w')
with open('read.txt') as f:
    for line in f: 
         #read a line
         a,b=line.split('\t')
         #get two values as string
         c=2*int(a)
         d=3*int(b)
         #calculate the other two values
         ### edited
         e = ''.join(("(",str(a),",",str(b),")"))

However, when I print e the last bracket will be moved to a new line:

        print(e)

will yield

     (1,2
     )
     (3,4
     ) 

but I want

     (1,2)
     (3,4) 

Thanks for your help!

1
  • 3
    Try line = line.replace("\n", "") before further processing the line. Commented Apr 10, 2019 at 23:24

2 Answers 2

2

It sounds like b has a \n (a newline character) at the end. b.strip() will return b with all of the whitespace on both sides removed. You could replace a,b=line.split('\t') with a,b=line.strip().split('\t')

or replace e = ''.join(("(",str(a),",",str(b),")")) with e = ''.join(("(",str(a),",",str(b.strip()),")"))

Sign up to request clarification or add additional context in comments.

Comments

0

You need to replace the \n in your lines before extracting your values. This should give the desired output:

with open('read.txt') as f:
    for line in f: 
         # read values
         a, b = line.replace("\n", "").split('\t')
         # get and parse values
         e = ''.join(("(",str(2*int(a)),",",str(3*int(b)),")"))
         print(e)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.