Tuesday, August 18, 2020

IslandT: Returns a sequence of all the even characters from a string with Python

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.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...