简体   繁体   中英

How can I sort a string that holds the representation of a list that follows JSON format in python

str1 = '["pwc","pok","Egyp", "$cur:USD", "ZAR"]'

I have the above string that holds the representation of a list that follows JSON format. I want to sort these values in alphabetical order and return a list. I did it in the below way:

def Convert(string):
    li = list(string.split(","))
    return li
  
# Driver code    
str1 = '["pwc","pok","Egyp", "$cur:USD", "ZAR"]'
print('Before sort')
print(str1)
lst = Convert(str1.strip("[]"))
print(lst)
print('After sort')
lst.sort()
print(lst)

The output I'm getting is [' "$cur:USD"', ' "ZAR"', '"Egyp"', '"pok"', '"pwc"']

But I want it in the below format(basically without the single quote(') between each values):

["$cur:USD","ZAR","Egyp","pok","pwc"]

Can anyone please help me in this.

To clarify you

  • don't have "string which contains a list of string values"
  • have "a string that holds the representation of a list that follows JSON format

So use json to load it, from string representation to python object

import json

str1 = '["pwc","pok","Egyp", "$cur:USD", "ZAR"]'
lst = sorted(json.loads(str1))
print(lst)  # ['$cur:USD', 'Egyp', 'ZAR', 'pok', 'pwc']
str1 = '["pwc","pok","Egyp", "$cur:USD", "ZAR"]'    
print(sorted(eval(str1)))

Warning: Use only if str1 is trusted input and you're sure that str1 is a valid python list

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