Подавите указание u'prefix unicode' в строках Python

Пришлось вызвать отдельную сортировку вставки, которая принимала дополнительные параметры для скорректированных индексов

48
задан Ryan 17 April 2009 в 17:22
поделиться

2 ответа

You could use Python 3.0.. The default string type is unicode, so the u'' prefix is no longer required..

In short, no. You cannot turn this off.

The u comes from the unicode.__repr__ method, which is used to display stuff in REPL:

>>> print repr(unicode('a'))
u'a'
>>> unicode('a')
u'a'

If I'm not mistaken, you cannot override this without recompiling Python.

The simplest way around this is to simply print the string..

>>> print unicode('a')
a

If you use the unicode() builtin to construct all your strings, you could do something like..

>>> class unicode(unicode):
...     def __repr__(self):
...             return __builtins__.unicode.__repr__(self).lstrip("u")
... 
>>> unicode('a')
a

..but don't do that, it's horrible

40
ответ дан 26 November 2019 в 18:40
поделиться

Я знаю, что это не глобальная опция, но вы также можете подавить Unicode u, поместив строку в функцию str ().

Итак, список, производный от Unicode, который будет выглядеть например:

>>> myList=[unicode('a'),unicode('b'),unicode('c')]
>>> myList
[u'a', u'b', u'c']

будет выглядеть так:

>>> myList=[str(unicode('a')),str(unicode('b')),str(unicode('c'))]
>>> myList
['a', 'b', 'c']

Это немного громоздко, но может быть полезно кому-то

4
ответ дан 26 November 2019 в 18:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: