Learner
Learner

Reputation: 511

Optional argument constraint

Framework: Robot, Language: Python-3.7.1 Proficicency: Novice

I am having the below core method which replace dynamic positions upon matching and widely being used in my existing automation scripts.

 def querybuilder(self, str, symbol, *args):
        count = str.count(symbol)
         str = list(str)
        i = 0
        j = 0
        if (count == (len(args))):
            while (i < len(str)):
                if (str[i] == symbol):
                    str[i] = args[j]
                    j = j + 1
                i = i + 1
        else:
            return ("Number of passed arguments are either more or lesser than required.")
        return ''.join(str)

This works fine if arguments sent like below

def querybuilder("~test~123", "~", "foo","boo")

But If I wanted to send as a list in place of optional argument, it takes each list/tuple/array as one parameter and therefore not going inside if condition.

For example:-

i = ["foo", "boo"] -- Optional argument consider it as ('foo, boo',)

Apparently, I can't make any changes in the method(querybuilder) because of -ve impact due to wide usage in existing framework.

What I tried so for to get rid of:-

1, ", ".join("{}".format(a) for a in i,
2, tuple(i),
3, list(i),
4, numpy.array(i) part of import numpy

Any possible solution to convert the parameters as per requirement?

Upvotes: 2

Views: 178

Answers (1)

AlanK
AlanK

Reputation: 9853

Pass your list in as *['foo', 'boo']

def querybuilder(s, symbol, *args):
    count = s.count(symbol)
    st = list(s)
    i = 0
    j = 0
    if (count == (len(args))):
        while (i < len(st)):
            if (st[i] == symbol):
                st[i] = args[j]
                j = j + 1
            i = i + 1
    else:
        return ("Number of passed arguments are either more or lesser than required.")
    return ''.join(st)

print(querybuilder("~test~123", "~", "foo","boo"))
# footestboo123
print(querybuilder("~test~123", "~", *["foo","boo"]))
# footestboo123

Upvotes: 2

Related Questions