In this example, I will write a Python function that will return a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return “invalid string”.

For example:

“abcdefghijklm” –> [“b”, “d”, “f”, “h”, “j”, “l”]
“a” –> “invalid string”

The solution is pretty simple, you certainly can write a shorter program but I do prefer to write a better program which will clearly show what this function is doing.

def even_chars(st): 
    li_s = []
    if(len(st) < 2 or len(st) > 100):
        return "invalid string"
    li = list(st)
    for i in range(0, len(st)):
        if(i%2 != 0):
            li_s.append(li[i])
    return li_s

The list starts from index 0, therefore I will write an if statement to test whether the number is an odd number or not, if the number is an odd number then it will be appended into the list which will be returned to the caller of the function.

Click to rate this post!
[Total: 5 Average: 1]
Please follow and like us:

5 Comments

  1. You can do this much more easily with string slicing:

    >>> def even_chars(st):
    … return st[::2]

    >>> even_chars(“abcdefghijklmnopqrstuvwxyz”)
    ‘acegikmoqsuwy’

    I know you said “you certainly can write a shorter program but I do prefer to write a better program which will clearly show what this function is doing”, but I feel slicing is clearer.

  2. A simpler version would be:

    def even_chars(st):
    if 2 <= len(st) <= 100:
    return list(st[1::2])
    else:
    return "invalid string"

  3. Please give up python programming as you are obviously clueless, this being at least the third poor example that you’ve put up Your output doesn’t even match your requirement and you can in any case do the entire thing in one line with a slice.

Leave a Reply

Your email address will not be published. Required fields are marked *