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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Cr1064
  • 409
  • 5
  • 15

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,726
  • 1
  • 10
  • 19
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,613
  • 4
  • 34
  • 55
  • 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