If statement about whether a single line or list of lines

I have the following function. Ideally, I want to have either a single line or a list of lines passed as input. In any case, I need to use .upper. But, when only one line is passed, the iterator iterates through each character. How can I use an if statement that checks if a list of lines or a single line contains? (I cannot escape the infinite nature of the strings)

def runthis(stringinput):

    for t in stringinput:
        t = t.upper()
+4
source share
4 answers

Check type with isinstance.

def runthis(stringinput):
    if isinstance(stringinput, list):
        for t in stringinput:
            t = t.upper()
            # Some other code should probably be here.
    elif isinstance(stringinput, basestring):
        t = t.upper()
        # Some other code perhaps as well.
    else:
        raise Exception("Unknown type.")

Use strinstead basestringfor Python 3.

+4
source

isinstance(), , arg list :

def to_upper(arg):
    if isinstance(arg, list):
        return [item.upper() for item in arg]  # This is called list comprehension
    else:
        return arg.upper()
+1

- , , - .

, , , ( ) :

def runthis(*stringinput):
    for t in stringinput:
        t = t.upper()
        print(t)
    print()

runthis("test") # TEST
runthis("another", "test")  # ANOTHER TEST
runthis(*["one", "final", "test"]) # ONE FINAL TEST

, .


*, .

(*stringinput) stringinput ; , "" , , , runthis ( ). runthis("foo", "bar", "baz"), stringinput ("foo", "bar", "baz").

.

(runthis(*["one", "final", "test"])) "" . , runthis(*["one", "final", "test"]) runthis("one", "final", "test").

splatting .

+1

You can use the function type()like this:

if type(stringinput) is list:
    #Your list code
elif type(stringinput) is str:
    #Your string code
else:
    #stringinput isn't a list or a string, throw an error
0
source

Source: https://habr.com/ru/post/1667038/


All Articles