Home > other >  Remove newline from string output
Remove newline from string output

Time:02-10

try:
    with cx_oracle.connect(user,password,dsn,encoding ="UTF-8") as connection:                      
        cursor = connection.cursor()                                                                  
        cursor.execute("select * from customer")                                                       
        results =cursor.fetchall()                                                                      
        return json.dumps(results,indent=4,sort_keys = True,default=str)                                                   
except Exception as error:                                                                            
    print ("error occurred",error)  

output

'[\n [\n 1456,\n   "ice kle",\n  "2022:02:08 8:06:01",\n  "2022-02-08 8:07:01",\n "fund"\n]'                                                                                                                                                                                                       

CodePudding user response:

just dont tell it to format the json

json.dumps(results) instead of json.dumps(results,indent=4...)

if you really just want to keep that json dumps for some reason and instead remove the newlines ... just do

result = result.replace("\n","")

CodePudding user response:

Better replace the '\n' with ''
result = result.replace('\n','')

CodePudding user response:

The indent=4 argument in json.dumps call is responsible for the pretty print(with newlines).
Remove the argument if want all of the result in single line.

@Joran 's answer is correct. I don't have the reputation to add a comment so adding it as answer.

  • Related