Search code examples
pythonstringsplitquotes

remove single quotes in list, split string avoiding the quotes


Is it possible to split a string and to avoid the quotes(single)?

I would like to remove the single quotes from a list(keep the list, strings and floats inside:

l=['1','2','3','4.5']

desired output:

l=[1, 2, 3, 4.5]

next line works neither with int nor float

l=[float(value) for value in ll]

Solution

  • To get int or float based on what each value looks like, so '1' becomes 1 and "1.2" becomes 1.2, you can use ast.literal_eval to convert the same way Python's literal parser does, so you have an actual list of ints and floats, rather than a list of str (that would include the quotes when echoed):

    >>> import ast
    >>> [ast.literal_eval(x) for x in l]
    [1, 2, 3, 4.5]
    

    Unlike plain eval, this doesn't open security holes since it can't execute arbitrary code.

    You could use map for a mild performance boost here (since ast.literal_eval is a built-in implemented in C; normally, map gains little or loses out to list comprehensions), in Py 2, map(ast.literal_eval, l) or in Py3 (where map returns a generator, not a list), list(map(ast.literal_eval, l))

    If the goal is purely to display the strings without quotes, you'd just format manually and avoid type conversions entirely:

    >>> print('[{}]'.format(', '.join(l)))
    [1, 2, 3, 4.5]