Python – How can I get a loop to ignore non-alphabetic elements in a list?

How can I get a loop to ignore non-alphabetic elements in a list?… here is a solution to the problem.

How can I get a loop to ignore non-alphabetic elements in a list?

I have a string that contains letters and punctuation. I’m trying to replace only the letters in this string with other ones. The function I developed only works with strings that contain letters. If numbers are included, a logic error is generated; If punctuation is included, a run-time error occurs. Anyway, can I get my function to ignore punctuation and leave it as it is, while only operating on letters?

#Create a string variable, ABjumbler generates an alphabet shifted by x units to the right
#ABshifter converts a string using one type to another

textObject = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
smalltext = 'abcde'

alphabet = list(['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'])

def ABjumbler(alphabet, x):
    freshset = []
    i=0
    j=0
    while i<(len(alphabet)-x):
        freshset.extend(alphabet[i+x])
        i+=1
    while j<x:
    freshset.extend(alphabet[j]) #extend [0]
    j+=1 #change j = to 1, extends by [1], then by [2], and then terminates when it reaches x
    alphabet = freshset
    return alphabet

newAlphabet = ABjumbler(alphabet, 2)

def ABshifter(text, shiftedalphabet):
    freshset = []
    for letters in text:
        position = text.index(letters)
        freshset.extend(shiftedalphabet[position])
    final = ''.join(freshset)
    return final

print ABshifter(smalltext, newAlphabet)

Solution

First, there are some faster/easier ways to make the conversion you want.

But to answer your question, you can simply add:

if not letter.isalpha():
    continue

str.isalpha() returns True if the string consists only of letters.

Related Problems and Solutions