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

Wirawan Purwanto
  • 3,613
  • 3
  • 28
  • 28
  • 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)))` – Jimmy Sep 09 '11 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))` – agf Sep 09 '11 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. – Wirawan Purwanto Sep 09 '11 at 17:39

3 Answers3

1

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

Some good links here and here

Community
  • 1
  • 1
hymloth
  • 6,869
  • 5
  • 36
  • 47
  • 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. – Wirawan Purwanto Sep 09 '11 at 17:42
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: {}

0

See the built-in eval() function.

Alex Smith
  • 1,495
  • 12
  • 13