0

I have a python string like this:

expression = "test[1]"

var1 = "{%s}" % expression
str1 = f"{var1}"
print(str1.format(test="world"))

I can only change the first line (expression affectation) and i want to test if second character is 'o' inside the expression, in order to display result on console.

if have tried this:

expression = "test[1]=='o'"

expression = "(test[1]=='o')"

expression = "1 if test[1]=='o' else 0"

Nothing works.

Is there a way to do this ?

Thanks

1 Answer 1

0

Try to create your own class that inherits the str class like this:

class MyStr(str):
    def __getattribute__(self, item):
        if "(" in item:
            return eval(f"'{self}'.{item}")
        return str.__getattribute__(self, item)

    def __getitem__(self, item):
        return MyStr(str.__getitem__(self, item))

Use your class in format method argument like this:

expression = "test[1].__eq__('o')"
str1 = f"{{{expression}}}"
print(str1.format(test=MyStr("world")))

Output

True

Be very careful when using the eval method because the usage shown is similar to sql injection.

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

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.