I am working with a module called PyDictionary
. Whenever it gets the synonym of a word, it creates a list
of the synonyms, however when I try print
the list
, it has a 'u'
before the synonym, example:
[u'welcome', u'howdy', u'hi', u'greetings', u'bonjour']
I've tried: synonym = re.sub('u','',synonym[0])
, and this works, but only prints 'welcome'
, not the entire list
.
Any help would be greatly appreciated. Thanks!
如果要将list
转换为strings
list
,可以使用list
推导,例如:
result = [str(x) for x in synonym]
The u
you are seeing is not part of the string content, and therefore cannot be removed with regular expression substitution. Instead, it should be considered part of the opening quote . The syntax of the Python language itself allows for string literals to be defined with quotes that are inflected in this way. For example:
a = 'spam'
b = u'spam' # in Python 2, a and b are different types
When you display the variable the way you would to a programmer , ie in such a way that the quote characters are visible (eg just typing synonym[0]
at the prompt, or trying to print
the whole list synonym
, or otherwise invoking Python's repr()
mechanism on the strings) then the u
will be visible too. By contrast, when you display the variable as you would to a user (eg with print synonym[0]
, or by join
ing the list and then print
ing the resulting string) then, just as you would not expect to see the quote characters themselves, you will also not see the u
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.