0

Suppose I have a string like this:

s="b a[1] something funny"

and I have these variables

b="10"
a=["1","is"]

is it possible for me to somehow replace values in the first string with values from my variables, hopefully with one function. I don't want to execute the string with eval because it contains invalid Python code.

4
  • 1
    You should try to turn your string into anything suitable for .format() method Commented Nov 17, 2015 at 11:59
  • Please correct the name of your variables, there is two s. Commented Nov 17, 2015 at 12:04
  • Thanks I didn't notice. Corrected mistake. Commented Nov 17, 2015 at 12:09
  • Can't test right now but I suposse .format() would help : s = "{} {} something funny".format(b,s[0]) Commented Nov 17, 2015 at 12:10

5 Answers 5

2
            s="b sx[1] something funny"
            b="10"
            sx=["1","is"]
            map = {}
            for i in range(0,len(sx)):
                map["sx["+str(i)+"]"]=sx[i]
            map['b'] = b
            lis = s.split(" ")
            ans = []
            for i in range(0,len(lis)):
                try:
                    ans.append(map[lis[i]])
                except Exception, e:
                    ans.append(lis[i])
            ans = " ".join(ans)
            print ans

Hope this helps

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

Comments

1

You could use this kind of formatting:

s = '{b} {a} something funny'.format(b="10", a=["1","is"])

3 Comments

Is it possible to do this without defining values for variables in .format() function?
Yes ! just define the variables before that call.
Can you edit your post to include what you are trying ? ( Multiple edits not overwriting the original version so it can serve as a tracking point )
1

That does the work, at least on your example:

b="10"
a=["1","is"]

def protectedEval(mystr):
    ret = []                       
    for i in mystr.split():
        try:
            ret.append(eval(i))
        except NameError:
            ret.append(i)
    return ' '.join(ret)

protectedEval("b a[1] something funny")

But you probably should use either .format or %.

Comments

0

In yet to be released Python 3.6 you can use Literal String Interpolation. For example:

>>> b = "10"
>>> a = ["1", "is"]
>>> s = f"{b} {a[1]} something funny"
>>> print(s)
10 is something funny

Comments

0

If you could turn your string template into a 'formattable' one, this should work:

s="{b} {a[1]} something funny"
b="10"
a=["1","is"]
print s.format(**locals())

10 is something funny

Although you should avoid locals() in favour of an esplicit dictionary:

s="{b} {a[1]} something funny"
parms = dict(
             b="10",
             a=["1","is"]
            )
print s.format(**parms)

10 is something funny

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.