0

I was wondering what the most pythonic way would be to check if a function input is a string or a list. I want the user to be able to enter a list of strings or a string itself.

def example(input):

   for string in input:

       #Do something here.
       print(string)

Obviously this will work in the input is a list of strings but not if the input is a single string. Would the best thing to do here is add type checking in the function itself?

def example(input):

    if isinstance(input,list):
       for string in input:
           print(input)
           #do something with strings
    else:
        print(input)
        #do something with the single string

Thanks.

Cr1064
  • 389
  • 3
  • 13

2 Answers2

0

Your code is fine. However you mentioned the list should be a list of strings:

if isinstance(some_object, str):
    ...
elif all(isinstance(item, str) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
    ...
else:
    raise TypeError # or something along that line

Check if input is a list/tuple of strings or a single string

ALFA
  • 1,706
  • 1
  • 9
  • 18
0

The second approach is fine, except that it should do with print(string_) and not print(input), if it matters:

def example(input):
    if isinstance(input,list):
       for string_ in input:
           print(string_)
           #do something with strings
    else:
        print(input)
        #do something with the single string


example(['2','3','4'])
example('HawasKaPujaari')

OUTPUT:

2
3
4
HawasKaPujaari
DirtyBit
  • 16,151
  • 4
  • 28
  • 54
  • 1
    Sorry yeah this is correct it was a typo in my original code. As long as this type checking of the list is considered alright style wise I'm happy enough. – Cr1064 Mar 05 '19 at 10:50