'Embedding executable python script in python string

If you are a bash/posix sh wizard you will know the $(command substition) feature in bash, which could even be inserted in a string. For example,

$ echo "I can count: $(seq 1 10 | tr -d '\n')" 
I can count: 12345678910

You can imagine all wild things to do with this, especially to make a dynamically formed string. No need to do if..else block outside the string; just embed the code inside! I am s spoiled by this feature. So here's the question: in python, can we do something similar? Is there one person already devising a module to accomplish this task?

(Just a side comment: admittedly having this kind of feature is powerful but also opening yourself to a security risk. The program can be vulnerable to code injection. So think thoroughly before doing this especially with a foreign string coming from outside the code.)



Solution 1:[1]

You can use eval() and all of it's potential risks...

Some good links here and here

Solution 2:[2]

See the built-in eval() function.

Solution 3:[3]

Are you looking for an fstring: Instead of starting the string with ' We start the string with f' And whenever we want to embed any script we just put inside these: {}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Alex Smith
Solution 3 Shaurya Chhabra