1

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.)

3
  • 3
    I don't see how print "I can count: $(''.join(map(str,range(1,11))))" is any better than, for example, print "I can count: %s" % ''.join(map(str,range(1,11))) Commented Sep 9, 2011 at 16:48
  • Yeah, you can do this kind of thing in Python without eval and friends. @Jimmy nothing wrong with your answer, or join(str(x) for x in range(1, 11)) Commented Sep 9, 2011 at 17:32
  • Just for clarity: I don't intend to reproduce that same exact action (in the snippet) in python. Not at all. I am making an input file for a scientific code and usually some parameters (say, nexpand) can depend on another parameter (say, size) in a fancy way. Commented Sep 9, 2011 at 17:39

3 Answers 3

1

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

Some good links here and here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the pointer. They are very interesting (I keep them in my clipping)! But in my question I am not concerned with security issues at all, since these are all private scripts and won't be run in a server at large. The strings to be executed will be my string, not a foreign string. I am just attaching the parenthetical comment so other people would not blindly use this technique without knowing what they are getting into.
0

See the built-in eval() function.

Comments

0

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: {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.