gpt4 book ai didi

python - 我怎样才能得到一个循环来忽略列表中的非字母元素?

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:49 25 4
gpt4 key购买 nike

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

#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)

最佳答案

首先,有一些更快/更简单的方法来进行您想要的转换。

但要回答您的问题,您可以简单地添加:

if not letter.isalpha():
continue

str.isalpha() 如果字符串仅由字母组成,则返回 True

关于python - 我怎样才能得到一个循环来忽略列表中的非字母元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18163230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com