python skipping '\n' in the replace method -
the below json,this read data->
[ { "name": "abc", "state": "ma", "statements": [ "set x=abc", "use @{domain}", "create table def" ], "parameters": [ {"name": "domanin", "required": true, "description": "this domain name"} ] } ]
=======================================================================================
import re; import sys; import json; loc_file=str(sys.argv[1]) ; open_json=open(loc_file); data=json.load(open_json); list1=data[0].get('statements'); json_input_string=""; json_input_string=str(list1); json_input_string=json_input_string.replace(r"text ' ' followed text",r"text '\n'"); # replace works fine replace below fails '\n' f = open("text.txt","w"); m="" c in list1: #print "\n\n"+c m=str(c).replace(r"text ' '",r"text '\n'"); # here fails (does not preserve 'n') f.write(m+";\n")
there 2 possible things of either possible solution 1) : if replace method works inside loop trying replace @ 2 places, replace function raw string notation works above variable
json_input_string
same replace fails when try inside loop oflist1
.(list1 has data in unicode format [u' set variable text ' ' ',u'expression text ' ' in table'] of python read write functions have tried far fail when need
'\n'
kept in replacement string.) or possible solution 2) if json_input_string can give me data in desired format when print json_input_string gives me output below though type 'str':
json_input_string=[u'set x=abc', u'use @{domain}', u"create table def"]
some have single quotes , have double quotes. want convert string output without single/double quotes , write file.
set x=abc; use @{domain}; create table def
m = str(c).replace(...)
new string in m
, not c
. python strings immutable.
Comments
Post a Comment