如何从字符串中识别非字母

2024-03-28 11:38:50 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好:)我正在构建一个脚本,用一个简单的文本旋转(ROT)来编写文本。 这个脚本运行得很好,但我有一个问题,它也会旋转所有符号,比如[空格,!,?,.]我正在使用ascii表来做这件事,我能做些什么来避免旋转这种类型的字符?你知道吗

def rot13(input,key): #Function to code a text with caeser chyper.
    if key > 25:
        key = 25
    elif key < 2:
        key = 2
    finaltext = ''
    for letter in input:
        num = ord(letter)
        if (num + key) > 122: #If the final number is greater than 122..
            x = (num + key) - 122
            finaltext += chr(x + ord('a') - 1)
        elif((num + key <= 122)):
            finaltext += chr(num + key)
    print(finaltext)

Tags: key文本脚本inputifascii符号num
2条回答

试试这个:

>>> import string
>>> letter = 'a'
>>> letter in string.letters
True
>>> letter = '.'
>>> letter in string.letters
False

在“旋转”您的角色之前,请添加一个检查以查看它是否为字母数字:

if letter.isalpha():
    # Do your thing
else:
    finaltext += letter

相关问题 更多 >