Create a representation of a Unicode string that can be used in both Python 2 and Python 3k, allowing for use of the u() function
(s)
| 109 | |
| 110 | |
| 111 | def rpr(s): |
| 112 | """Create a representation of a Unicode string that can be used in both |
| 113 | Python 2 and Python 3k, allowing for use of the u() function""" |
| 114 | if s is None: |
| 115 | return 'None' |
| 116 | seen_unicode = False |
| 117 | results = [] |
| 118 | for cc in s: |
| 119 | ccn = ord(cc) |
| 120 | if ccn >= 32 and ccn < 127: |
| 121 | if cc == "'": # escape single quote |
| 122 | results.append('\\') |
| 123 | results.append(cc) |
| 124 | elif cc == "\\": # escape backslash |
| 125 | results.append('\\') |
| 126 | results.append(cc) |
| 127 | else: |
| 128 | results.append(cc) |
| 129 | else: |
| 130 | seen_unicode = True |
| 131 | if ccn <= 0xFFFF: |
| 132 | results.append('\\u') |
| 133 | results.append("%04x" % ccn) |
| 134 | else: # pragma no cover |
| 135 | results.append('\\U') |
| 136 | results.append("%08x" % ccn) |
| 137 | result = "'" + "".join(results) + "'" |
| 138 | if seen_unicode: |
| 139 | return "u(" + result + ")" |
| 140 | else: |
| 141 | return result |
| 142 | |
| 143 | |
| 144 | def force_unicode(s): |
no test coverage detected