2

First of all, I do realize that this is a really simple question and please bear with me on this.

How, in python, can I get the numbers of strings? I am trying to do something like this:

def func(input_strings):
    # Make the input_strings iterable
    if len(input_strings) == 1:
        input_strings = (input_strings, )
    # Do something
    for input_string in input_strings:
        analyze_string(input_string)
    return

So with this function, if the input is a list, ['string1', 'string2', 'string3'], it will loop over them; if the input is only one string like 'string1', then it will still take care of it, instead of throwing an exception.

However, the len(str) returns the number of characters in the string and wouldn't give me a "1".

I'd really appreciate your help!

4

2 回答 2

5

Use isinstance to check whether a given value is string:

>>> isinstance('a-string', str)
True
>>> isinstance(['a-string', 'another-string'], str)
False

def func(input_strings):
    # Make the input_strings iterable
    if isinstance(input_strings, str):
        input_strings = (input_strings, )
    # Do something
    for input_string in input_strings:
        analyze_string(input_string)
    return

Python 2.x note (Python 2.3+)

Use isinstance('a-string', basestring) if you want to also test unicode. (basestring is the superclass for str and unicode).

于 2013-09-12T01:45:32.267 回答
4

I'd suggest using *args to allow the function to accept any number of strings.

def func(*input_strings):
    for input_string in input_strings:
        analyze_string(input_string)

func("one string")
func("lots", "of", "strings")

If you then want the number of strings, you can simple use len(input_strings).

Have a look at these answers.

于 2013-09-12T02:29:13.903 回答