Home > Net >  add " characters in write function python
add " characters in write function python

Time:05-05

I have a code that emits this output

file.write(row['time']   "{application="   row['application']   ",runtime="   str(row['runtime'])   "} "   row['value']   "\n")

output:

folder_put_time{application=app1,runtime=1231231231} 17

I want the format to be as following:

folder_put_time{application="app1", runtime="1231231231"} 19

How can I add the " sign in code? "/"" didn't work for me

Thanks

CodePudding user response:

Since your data is already in a dict (or a mapping object anyway), I think the cleanest option here is to use str.format_map (though the double {{ }} to escape the other quotes are a bit ugly still:)

file.write('{time}{{application="{application}",runtime="{runtime}"}} {value}\n'.format_map(row))

You could use \" to escape quotes:

file.write(row['time']   "{application=\""   row['application']   "\",runtime=\""   str(row['runtime'])   "\"} "   row['value']   "\n")

or use a single-quoted string and just use plain " within the string:

file.write(row['time']   '{application="'   row['application']   '",runtime="'   str(row['runtime'])   '"} '   row['value']   '\n')

You could also use an f-string for less str() casts, but accessing dicts within an f-string is a bit ugly (and curly braces need to be escaped by doubling).

file.write(f'{row["time"]}{{application=\"{row["application"]}\",runtime=\"{row["runtime"]}\"}} {row["value"]}\n')
  • Related