Your real issue here seems to be the fact you are getting the representation of a value rather than the value.
>>> x = u"gcc-4.3.2"
>>> x
u'gcc-4.3.2'
>>> repr(x)
"u'gcc-4.3.2'"
>>> str(x)
'gcc-4.3.2'
If you have any control over the place you are getting the value from, I would go there first and deal with that.
Warning: Unicode is different for a reason, if you have unicode characters, you can run into issues:
>>> x = u"ĝĝ"
>>> x
u'\u011d\u011d'
>>> repr(x)
"u'\\u011d\\u011d'"
>>> str(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
If you have no control over the data you are getting, the value of repr(x)
is an expression you can evaluate:
>>> x = "u'gcc-4.3.2'"
>>> eval(x)
u'gcc-4.3.2'
However, do note that eval is highly unsafe for a number of reasons.
If you want to deal with extracting the unicode strings more safely, you could do something like this:
>>> import re
>>> x = "u'gcc-4.3.2' u'C'"
>>> re.findall("u'(.*?)'", x)
['gcc-4.3.2', 'C']
Here we use a regular expression to extract anything in the string encased in u''
. We use .*?
to make the operation non-greedy, ensuring we don't end up with ["gcc-4.3.2' u'C"]
as our output.