简体   繁体   中英

Print string in one line

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!

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()),")"))

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)

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