#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Indexing a string! Help me!


    My question is:
    Words that start with a vowel or y and end with a vowel or y.

    So far I have,

    Code:
    def start_end_vowel(s):
    	for i in range(0, len(s)-5):
    		if (s[0] == 'a' or s[0] == 'e' or s[0] == 'i' or s[0] == 'o' or s[0] == 'u' or s[0] == 'y') and (s[len(s)-5] == 'a' or s[len(s)-5] == 'e' or s[len(s)-5] == 'i' or s[len(s)-5] == 'o' or  s[len(s)-5] == 'u' or s[len(s)-5] == 'y'):
    			return True
    	return False

    There must be an easier method than this..... please help!!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    76
    Rep Power
    2
    Could you post some input and output examples?

    and instead of doing
    if (s[0] == 'a' or s[0] == 'e' or s[0] == 'i' or s[0] == 'o' or s[0] == 'u' or s[0] == 'y')

    you could just do
    if s[0] in "aeiouy"

    and maybe read up on slicing? Slicing is really powerful.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    76
    Rep Power
    2
    btw,
    "hello"[-1] returns an "o" because the index -1 is the last letter in the string.
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Iran
    Posts
    148
    Rep Power
    139
    Originally Posted by laffytaffykidd
    ... There must be an easier method than this..... please help!!
    I use a regular expression for this problem, something like this:
    Code:
    import re
    
    def checkForLetters(param_Text):
        prog = re.compile("^[aeiouy].*[aeiouy]$(?i)") 
        if prog.match(param_Text):
            return True
        else:
            return False
    For more information about regular expressions, please read RE - Regular expression operations


    Regards,
    Dariyoosh
  8. #5
  9. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Iran
    Posts
    148
    Rep Power
    139
    And if you don't want to use regular expressions for this problem, another solution could be this
    Code:
    def checkForLetters(p_text):
        l_lettersList = ["a", "e", "i", "o", "u", "y"]
        l_lowerTxt = p_text.lower()
        return (
                    l_lowerTxt[0] in l_lettersList and 
                    l_lowerTxt[-1] in l_lettersList
                )
    Regards,
    Dariyoosh
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    If you're only using it for "in" checks, you should be using a set, not a list.

    But yeah, that's the way to do it.

IMN logo majestic logo threadwatch logo seochat tools logo