How to avoid string for generated C ++?

I am writing a python script that generates C ++ code based on data.

I have a python variable stringthat contains a string that can be composed of type characters "or newlines.

What is the best way to avoid this line for code generation?

+5
source share
2 answers

The way I use is based on the observation that C ++ strings basically obey the same rules regarding characteristics and escaped as a Javascript / JSON string.

Python, since version 2.6 has a built-in JSON library that can serialize Python data into JSON. Therefore, the code, assuming that we do not need a quote, namely:

import json
string_for_printing = json.dumps(original_string).strip('"')
+3
source

, :

def string(s, encoding='ascii'):
   if isinstance(s, unicode):
      s = s.encode(encoding)
   result = ''
   for c in s:
      if not (32 <= ord(c) < 127) or c in ('\\', '"'):
         result += '\\%03o' % ord(c)
      else:
         result += c
   return '"' + result + '"'

escape-, .

+1

All Articles