3

I'd like to unencapsulate a string (in Python) from another string.

For example, from:

>>> string1
"u'abcde'"

I'd like to get:

>>> string2
'abcde'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
gbajson
  • 1,531
  • 13
  • 32

1 Answers1

1

Seems like you want the function eval

>>> stri = "u'abcde'"
>>> eval(stri)
'abcde'

>>> help(eval)
Help on built-in function eval in module builtins:

eval(...)
    eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

As per the below comments, you need to use ast.literal_eval function instead of in-built eval function because eval will evaluate arbitrary (and potentially dangerous) code, whereas ast.literal_eval will only evaluate Python literals.

>>> import ast
>>> stri = "u'abcde'"
>>> ast.literal_eval(stri)
'abcde'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274