Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add " characters in write function python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Thanks

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading