我有一个包含字母和标点符号的字符串。我试图只用其他字母替换这个字符串中的字母。我开发的函数只适用于包含字母的字符串。如果包含数字,则会产生逻辑错误,如果包含标点符号,则会产生运行时错误。无论如何,我可以让我的功能忽略标点符号并保持原样,同时只对字母进行操作?
#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)