Turn string or bytes to string >>> ensure_unicode('123') '123' >>> ensure_unicode(b'123') '123'
(s)
| 1120 | |
| 1121 | |
| 1122 | def ensure_unicode(s) -> str: |
| 1123 | """Turn string or bytes to string |
| 1124 | |
| 1125 | >>> ensure_unicode('123') |
| 1126 | '123' |
| 1127 | >>> ensure_unicode(b'123') |
| 1128 | '123' |
| 1129 | """ |
| 1130 | if isinstance(s, str): |
| 1131 | return s |
| 1132 | elif hasattr(s, "decode"): |
| 1133 | return s.decode() |
| 1134 | else: |
| 1135 | try: |
| 1136 | return codecs.decode(s) |
| 1137 | except Exception as e: |
| 1138 | raise TypeError( |
| 1139 | f"Object {s} is neither a str object nor can be decoded to str" |
| 1140 | ) from e |
| 1141 | |
| 1142 | |
| 1143 | def digit(n, k, base): |
no outgoing calls