简体   繁体   中英

Conversion of Strings to list

Can someone please help me with a simple code that returns a list as an output to list converted to string? The list is NOT like this:

a = u"['a','b','c']"

but the variable is like this:

a = '[a,b,c]'

So,

list(a)

would yield the following output

['[', 'a', ',', 'b', ',', 'c', ']']

instead I want the input to be like this:

['a', 'b', 'c']  

I have even tried using the ast.literal_eval() function - on using which I got a ValueError exception stating the argument is a malformed string.

There is no standard library that'll load such a list. But you can trivially do this with string processing:

a.strip('[]').split(',')

would give you your list.

str.strip() will remove any of the given characters from the start and end; so it'll remove any and all [ and ] characters from the start until no such characters are found anymore, then remove the same characters from the end. That suffices nicely for your input sample.

str.split() then splits the remainder (minus the [ and ] characters at either end) into separate strings at any point there is a comma:

>>> a = '[a,b,c]'
>>> a.strip('[]')
'a,b,c'
>>> a.strip('[]').split(',')
['a', 'b', 'c']

Let us use hack.

import string

x = "[a,b,c]"

for char in x:
    if char in string.ascii_lowercase:
        x = x.replace(char, "'%s'" % char)

# Now x is "['a', 'b', 'c']"
lst = eval(x)

This checks if a character is in the alphabet(lowercase) if it is, it replaces it with a character with single quotes around it.

Why not use this solution ?:

  • Fails for duplicate elements
  • Fails for elements with more than single characters.
  • You need to be careful about confusing single quote and double quotes

Why use this solution ?:

  • There are no reasons to use this solution rather than Martijn's. But it was fun coding it anyway.

I wish you luck in your problem.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM