Convert string to python code

How to Convert Strings to Python Types

In this article, you’ll learn how to convert strings of Python types to concrete Python types. The ability to convert strings to different Python types is important if you’re reading data from a file or relying on user input. We’ll walk you through the following methods for converting strings to Python types:

  • Converting Strings to integers
  • Converting Complex String Representations to Python Types
    • Using Custom Code
    • Using json.loads() method
    • Using ast.literal_eval() method

    Converting Strings to Integers

    In the next few sections you’ll see how string representation of complex Python types can be converted to concrete Python types, but before we do that, let’s look at a simple example of how you can convert strings of integers to actual integer types.

    The following script defines a string variable that stores an intege, 58, in a string format. The value and the type of the string variable is printed using the type() function. You can see that the variable type is str, meaning it’s a string.

    num = "58" print(num) print(type(num))

    To convert a string to an integer, you need to pass the string to the int() function, as shown in the following example.

    num2 = int(num) print(type(num2))

    The int() function throws an exception if you pass it a string of something other than an integer. Here’s an example.

    --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [3], in cell line: 2>() 1 num = "hello" ----> 2 num2 = int(num) ValueError: invalid literal for int() with base 10: 'hello'

    Converting Complex String Representations to Python types

    Let’s see to convert string representations of more complex Python types to concrete Python types.

    Converting Strings to Python Types via Custom Code

    You can write a custom piece of code to convert string representations of Python types into concrete Python type. However, it can be rather cumbersome. Let’s demonstrate this with the help of an example.

    The following script defines string representation of a Python list. If you check its type, you will see that its a string.

    colors = "['Orange', 'Green', 'Yellow', 'Blue', 'Red']" print(type(colors))

    To convert the string representation of the above list into a Python type, you need to do some string parsing.

    As a first step, you can remove leading and trailing square brackets and remove the quotes surrounding the individual list items. Here’s one way to do this:

    temp = colors.strip('[]').replace("'", "") print(temp) print(type(temp))
    Orange, Green, Yellow, Blue, Red class 'str'>

    Next, you can use the Python split() function to split the string using commas. The split() function returns the list of items, as shown in the following script.

    colors_list = temp.split(', ') print(colors_list) print(type(colors_list))
    ['Orange', 'Green', 'Yellow', 'Blue', 'Red'] class 'list'>

    The following script combines the above steps in single line of code.

    colors_list = colors.strip('[]').replace("'", "").split(", ") print(colors_list) print(type(colors_list))
    ['Orange', 'Green', 'Yellow', 'Blue', 'Red'] class 'list'>

    You can see that converting a string representation of a Python type to a concrete Python type, like a list, can be time-consuming and it can only be used for specific string formats. You’d have to write a different code for every Python type.

    Fortunately, there are easier ways to convert strings to Python types. We’ll go over these methods in the next couple sections.

    Get Our Python Developer Kit for Free

    I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.

    Converting Strings to Python Types using json.loads()

    You can use the loads() function from the Python json module to convert a string to a Python type.

    However, it’s important that the string representation of a Python type comply with the JSON format.

    For example, the following script will throw an exception since the list items are enclosed in single quotations, whereas the JSON expects list items to be enclosed in double quotations. For that reason, a basic familiarity with JSON is required when using the json.loads() function.

    import json colors = "['Orange', 'Green', 'Yellow', 'Blue', 'Red']" colors_list = json.loads(colors) print(colors_list) print(type(colors_list))
    JSONDecodeError: Expecting value: line 1 column 2 (char 1)

    In the following script, the items in the colors list are enclosed in double quotes, so the json.loads() function will successfully convert the string representation of the list to an actual Python list.

    colors = '["Orange", "Green", "Yellow", "Blue", "Red"]' import json colors_list = json.loads(colors) print(colors_list) print(type(colors_list))
    ['Orange', 'Green', 'Yellow', 'Blue', 'Red'] class 'list'>

    Converting Strings to Python Types using ast.literal_eval()

    Finally, you can use the literal_eval() function from the Python ast (Abstract Syntax Trees) module to convert a string to a Python type.

    The literal_eval() function is, by far, the safest option for converting a string to a Python type since it can convert string representations of Python types in a variety of formats.

    For example, the following script converts a string representation of a Python list with items enclosed in single quotes to a concrete Python list.

    import ast colors = "['Orange', 'Green', 'Yellow', 'Blue', 'Red']" colors_list = ast.literal_eval(colors) print(colors_list) print(type(colors_list))
    ['Orange', 'Green', 'Yellow', 'Blue', 'Red'] class 'list'>

    In the same way, you can convert a string representation of a Python list with double quotes, as shown below:

    colors = '["Orange", "Green", "Yellow", "Blue", "Red"]' colors_list = ast.literal_eval(colors) print(colors_list) print(type(colors_list))
    ['Orange', 'Green', 'Yellow', 'Blue', 'Red'] class 'list'>

    As a final example, our next script demonstrates how you can convert a string representation of a Python dictionary to an actual Python dictionary using the literal_eval() function.

    scores = "" scores_dict = ast.literal_eval(scores) print(scores_dict) print(type(scores_dict))
    'James': 10, 'John': 35, 'Sara': 40> class 'dict'>

    The string was successfully converted to a dictionary, with the keys being stored as strings and the values being stored as integers. Hopefully this example helped illustrate just how powerful the literal_eval() function is!

    Get Our Python Developer Kit for Free

    I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more — and I want you to have it for free. Enter your email address below and I’ll send a copy your way.

    About The Python Tutorials Blog

    Ryan Wells

    The Python Tutorials Blog was created by Ryan Wells, a Nuclear Engineer and professional VBA Developer. After launching his VBA Tutorials Blog in 2015, he designed some VBA Cheat Sheets, which have helped thousands learn to write better macros. He expanded in 2018 with The Python Tutorials Blog to teach people Python in a similar systematic way. Today, wellsr.com reaches over 2 million programmers each year!

    Источник

    Converting string to python code

    Hi all. Is there any way that if I give python a string, it can convert it into code? Example, say I am given this string:

    • 6 Contributors
    • 11 Replies
    • 11K Views
    • 5 Days Discussion Span
    • Latest Post 14 Years Ago Latest Post by abhigyan91

    How are you giving the strings?
    If you are giving a complete python program in the string, you do a trick:
    Write all the string into a file and execute it with the interpreter by using a execv or system command.

    Please know that this is a security risk. Use the exec function:

    You are loading code from a string into your application and running it. Unless you have compete and absolute control over the string (you create it yourself, and no part of it comes from outside our program), there is always a way for someone to inject some malicious code into …

    All 11 Replies

    How are you giving the strings?
    If you are giving a complete python program in the string, you do a trick:
    Write all the string into a file and execute it with the interpreter by using a execv or system command.

    You are loading code from a string into your application and running it. Unless you have compete and absolute control over the string (you create it yourself, and no part of it comes from outside our program), there is always a way for someone to inject some malicious code into your program.

    oh I see. lol with the stuff i’m working on, I won’t need to worry about that, but thanks for the tip!

    temp_string = "Vent( Screen, 100, 484, 'Vent' )"

    python doesn’t return anything (like init values that have been printed and returned statements). What could be the problem?

    What does it return, an error message? exec() will work on things like print statements or 1+2-3, but if you call a function or class then you must already have that function defined, otherwise an error message. Perhaps if you explained what you are trying to do, there would be an easier way, like a generic class that you would pass the strings in the file to as parameters —> some_class( the_string ).

    It doesn’t work, but I write up some code that (based of the strings from the text file) recognizes the first four characters in a line, a.k.a ‘Vent’, and then gets the string(s) from in between the characters ‘(‘ and ‘,’ and then ‘,’ and ‘,’. The last argument just stays a string. I then pass a new instance with those new given values. It’s no big deal if the exec thing doesn’t work, but thanks any ways

    The function exec() does not know where class Vent is coming from.
    You could try something like:
    exec(mystring, globals()) Now you are putzing around with the global dictionary, dangerous territory indeed!

    i think this should work.. i didn’t test it out yet coz this comp doesnt hav python installed. try it out n let me know..(im a noob tho.. dnt mind if it doesnt:))

    def str2code(s): if (s[0] == '\'' or s[0] == '\"') or (s[-1] == '\'' or s[-1] == '\"'): del s[0] del s[-1] return s #print str2code("testing")

    We’re a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.

    Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.

    Источник

    Читайте также:  Mysql connector java bin jar
Оцените статью