Search code examples
python-2.7formattingstartswith

Using startswith() with strings formatting operators


I have the following bits of code:

name = "Axe"
vowels = ["a","e","i","o","u"]    

if %s.startswith(vowels) % (name):    #name will be input from users
    print "sth"
else:
    ....

Here, I try to use the startswith function with strings formatting operators but it didn't work. I also tried with the {} format, but it still gives me a syntax error. Am I doing something wrong or this isn't possible? Thank you in advance.


Solution

  • It's a little unclear from your code exactly what you mean to do, but this works:

    >>> ("%s" % 'hi').startswith('h')
    True
    

    So I think that the problem is that you have to first format your string and then do .startswith(). Also I don't think that startswith accepts arrays as an argument so you would have to do something like

    if True in map(lambda x: ("%s" % name).startswith(x), vowels):
        # do something
    

    And furthermore if you want to ignore case you would do:

    if True in map(lambda x: ("%s" % name).lower().startswith(x), vowels):
        # do something
    

    Hope this helps!