【问题标题】:Get the character from the alphabet position in python从python中的字母位置获取字符
【发布时间】:2021-11-12 13:44:28
【问题描述】:

这段代码给出了字符的字母位置 我想要一个代码,我给出位置并返回字母表

from string import ascii_lowercase
LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)} 

def alphabet_position(text):
    text = text.lower()
    numbers = [LETTERS[character] for character in text if character in LETTERS]
    return ' '.join(numbers)

【问题讨论】:

标签: python


【解决方案1】:

就像@haveaball 所说,使用 Python 的基本功能更容易。如果您真的想使用 LETTERS 字典,那么您可以按照回答 here 来解决它。这将为您提供以下代码:

from string import ascii_lowercase
LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)} 

def alphabet_letter(text):
    text = text.lower()
    letters = [list(LETTERS.keys())[list(LETTERS.values()).index(character)] for character in text if character in LETTERS]
    return ' '.join(letters)

【讨论】:

    【解决方案2】:

    这是here 的回答。您可以使用一些内置的 Python 基础功能来使其工作,您实际上并不需要自己构建一个复杂的函数(尽管这可能是一个好习惯!)。

    【讨论】:

    • 谢谢,但这不是我想要的
    猜你喜欢
    • 2011-08-21
    • 2016-08-15
    • 2012-10-22
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 2021-09-12
    相关资源
    最近更新 更多