在python中,如何检查输入在特定索引位置是否有特定的字母?

2024-05-06 09:21:39 发布

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

我想写一个加密程序,把输入的字母变成数字。 我已经取得的成果是,例如,如果用户输入的第一个字母是a(或任何其他字母),它会打印出其连接的号码。但我无法使用循环,因此我必须这样做:

letter_1 = "a"
if (Text[0])== letter_1 :

print("20")
if (Text[1]) == letter_1:

print("20")

我对字母表中的每个字母都这样做了,但我不知道如何使用循环,尽管这会使一切变得更容易

总之,我的问题是,我必须复制整个字母表,并始终更改(文本[])编号,以便用户可以再输入一个字母


3条回答

首先,也是最重要的一点,不要在数据安全确实很重要的情况下使用手工加密-确保这是用于任务或宠物项目,而不是关键任务

至于完成任务,您可以从一个充当某种查找表的字典开始,比如

enc = {
  "a": 1,
  "b": 2,
  "c": 3,
  # Continue through the alphabet, including capital letters, spaces, symbols, etc.
}

从那里,你可以从你的用户那里得到一个字符串,然后你可以调用

encrypted = [enc[letter] for letter in user_input_string]

您可能会遇到没有放入enc字典的字符的问题,因此请确保尽可能完整

我已经创建了代码来解决您的问题,但理想情况下,您应该做一些关于循环和数据结构(如字典和列表)的基础知识。我会推荐你去HackerRank,它有基本的教程。你会发现它非常有用

## Importing randint to generate random numbers
from random import randint

## Create an empty dictionary to store character to number mapping, for example, a -> 21
encoding = {}
## Create a loop that runs 26 times
for i in range(26):
   ## convert 'a' to it's ORD form this is similar to ASCII and can be used to increment alphabets. Add the iteration number to the ORD value and convert it back to char
   key = char(ord('a') + i)
   ## Store the the encoding for the key, for example 'a'. The encoding will be a random number between 0 and 99
   encoding[key] = randint(99)

## Take user input
user_input = input('Enter a string to be encoded')
## Initialise the encoded message as an empty string
encoded_message = ''
## Create a loop that runs for the number of characters in the input string
for i in range(len(user_input)):
    ## Convert the character to lower case
    ch = lower(user_input[i])
    ## Find the mapping in encoding using get, it will return '' if no mapping is found for example if anything other than a alphabet is present.
    encoded_char = encoding.get(ch, '')
    ## Add the encoded char to the message
    encoded_message += encoded_char
## Print the encoded mesaage
print(encoded_message)

嗯,就像很多问题一样,把它分解成几个步骤是有帮助的。在本例中,您从纯文本开始,需要一次处理一个字符才能转换为加密文本

以下是字母表中前4个字母的示例,可以帮助您解决更大的问题:

# A dictionary to convert a letter into a (string version of a) number
encoder = {"a": "20", "b": "30", "c": "40"}

# The text to be encrypted
plain_text = "bbca"

# A loop to map the plain_text to encrypted_text
encrypted_text = ""
for plain_char in plain_text:
    encrypted_text = encrypted_text + encoder[plain_char]

print(encrypted_text)

输出:

30304020

相关问题 更多 >