Monday, November 19, 2018

Convert your string in python default types

 Convert your string in python default types



There are many possibilities while doing some complex programming and some data getting as string or JSON format but somehow it won't be converted into actual type like dictionary, list or tuple format.

Here you can find the alternate solution to get actual type using only few steps.

1) Open your terminal.

2) Type python [Python must be installed on your system.]

3) Past This example in your terminal.

#Import literal_eval python package
from ast import literal_eval

#Here is your string formatted dictionary
older_string = "{'a':123, 'b':}"

print older_string

#output as below
"{'a':123, 'b':}"

#Now using literal_eval lib to convert string to dictionary.
new_string = literal_eval(older_string)

print new_string

#output as below
{'a':123, 'b':}


NOTE :-
In case key value is missing than it won't be convert. it will throw exception.

 

No comments:

Post a Comment

If you have any query please comment here, Will get back to you :)