Return the position of the string’s characters from the character list with python

Here is one of the python code challenge question from a website: You need to find what is the position of each character in a string from a character list and then return that entire character positions in a single string with space between each character position excepts the last one. You need to ignore all those characters that are not in the character list which is consists of the character from a-z.

The strategy:

First we need to declare the list of a-z characters in a list.

alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

Next create a loop which will loop though each character in the string and find the position of each character in the character list above, if the character is not in the list then just skip the iteration and goes to the next one. We need to make sure the character has been converted to lowercase before the search begins as well as add 1 to the return index which will contain zero (we want our index to start at 1 instead of 0).

for ch in text:
        if(ch.lower() not in alphabetlist):
            continue
        else:
            ch = ch.lower()
            letterpos += str(alphabetlist.index(ch) + 1) + " "

Finally return the string of character positions and don’t forget to truncate the space at the end of the string. The full code is as follow:

def alphabet_position(text):
    if(len(text) == 0): # if the text is blank then return it
        return text

    alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    letterpos = ''
   
    for ch in text:
        if(ch.lower() not in alphabetlist):
            continue
        else:
            ch = ch.lower()
            letterpos += str(alphabetlist.index(ch) + 1) + " "
           
    return letterpos.rstrip()

Now we can call the function above with string parameter to see the outcome.

print(alphabet_position("Hello World!")) 

Copy the code above to Visual Studio Code and run the program by yourself to see the output!

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of