获取字母表中的字符位置

发布于 2024-11-05 21:54:41 字数 180 浏览 6 评论 0原文

我 90% 确信有一个内置函数可以做到这一点。

我需要找到字母表中字符的位置。所以字符“b”是位置1(从0开始计数),等等。有谁知道这个函数叫什么?

我想做的是将所有字符 X 数量的“步数”发送回字母赌注中,因此,如果我有一个带有“hi”的字符串,如果我将其发送回一步,它将是“gh”。可能有更好的方法,有什么建议吗?

I'm 90% sure there is a built in function that does this.

I need to find the position of a character in an alphabet. So the character "b" is position 1 (counting from 0), etc. Does anyone know what the function is called?

What I'm trying to do is to send all the characters X amount of "steps" back in the alpha bet, so if I have a string with "hi", it would be "gh" if I send it back one step. There might be a better way of doing it, any tips?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

朱染 2024-11-12 21:54:41

它称为索引。例如:

>>> import string
>>> string.ascii_lowercase.index('b')
1
>>> 

注意:在 Python 2 中,string.ascii_lowercase 被命名为 string.lowercase

It is called index. For example:

>>> import string
>>> string.ascii_lowercase.index('b')
1
>>> 

Note: in Python 2, string.ascii_lowercase was named string.lowercase.

墨小沫ゞ 2024-11-12 21:54:41

无需进口

def char_position(letter):
    return ord(letter) - 97

def pos_to_char(pos):
    return chr(pos + 97)

Without the import

def char_position(letter):
    return ord(letter) - 97

def pos_to_char(pos):
    return chr(pos + 97)
心房的律动 2024-11-12 21:54:41

您可以使用 ord() 获取字符的 ASCII 位置,并使用 chr() 将 ASCII 位置转换为字符。

例如:

my_string  = "zebra"
difference = -1
new_string = ''.join((chr(97+(ord(letter)-97+difference) % 26) for letter in my_string))

这将创建一个字符串,其中所有字符在字母表中向后移动一个空格('ydaqz')。它仅适用于小写单词。 a-1 映射到 z,z+1 映射到 a。

You can use ord() to get a character's ASCII position, and chr() to convert a ASCII position into a character.

For example:

my_string  = "zebra"
difference = -1
new_string = ''.join((chr(97+(ord(letter)-97+difference) % 26) for letter in my_string))

This will create a string with all the characters moved one space backwards in the alphabet ('ydaqz'). It will only work for lowercase words. a-1 maps to z and z+1 maps to a.

梨涡 2024-11-12 21:54:41
# define an alphabet
alfa = "abcdefghijklmnopqrstuvwxyz"

# define reverse lookup dict
rdict = dict([ (x[1],x[0]) for x in enumerate(alfa) ])

print alfa[1] # should print b

print rdict["b"] # should print 1

rdict 是通过逐步浏览字母表(一次一个字符)创建的字典。 enumerate 函数返回一个包含列表索引和字符的元组。我们通过使用以下代码创建一个新元组来反转顺序:(x[1], x[0]),然后将元组列表转换为字典。由于字典是哈希表(键,值)数据结构,因此我们现在可以查找任何字母字符的索引。

然而,这并不是你想要解决的问题,如果这是一个课堂作业,如果你提交它,你可能会因为抄袭而得到 0 分。为了对字符串进行编码,首先创建一个组织好的第二个字母表,以便 alfa2[n] 是 alfa[n] 的编码形式。在您的示例中,第二个字母表将仅移动两个字符,但您也可以随机打乱字符或使用其他模式对它们进行排序。所有这些都将继续适用于其他字母,例如希腊语、西里尔语等。

# define an alphabet
alfa = "abcdefghijklmnopqrstuvwxyz"

# define reverse lookup dict
rdict = dict([ (x[1],x[0]) for x in enumerate(alfa) ])

print alfa[1] # should print b

print rdict["b"] # should print 1

rdict is a dictionary that is created by stepping through the alphabet, one character at a time. The enumerate function returns a tuple with the list index, and the character. We reverse the order by creating a new tuple with this code: ( x[1], x[0]) and then turn the list of tuples into a dictionary. Since a dictionary is a hash table (key, value) data structure, we can now look up the index of any alphabet character.

However, that is not what you want to solve your problem, and if this is a class assignment you would probably get 0 for plagiarism if you submit it. For encoding the strings, first create a SECOND alphabet that is organised so that alfa2[n] is the encoded form of alfa[n]. In your example, the second alphabet would be just shifted by two characters but you could also randomly shuffle the characters or use some other pattern to order them. All of this would continue to work with other alphabets such as Greek, Cyrillic, etc.

攒眉千度 2024-11-12 21:54:41

我才刚刚开始学习Python,所以我不知道这与其他方法相比有多高效,但它确实有效。另外,文本是大写、小写还是有标点符号等并不重要。

如果您想更改所有字母:

from string import maketrans

textin = "abcdefghijklmnopqrstuvwxyz"
textout = "cdefghijklmnopqrstuvwxyzab"
texttrans = maketrans(textin, textout)

text = "qcc, gr umpiq"

print text.translate(texttrans)

也可以更改某些字符:

from string import maketrans

textin = "81972"
textout = "Seios"
texttrans = maketrans(textin, textout)

text = "811, 9t w7rk2"

print text.translate(texttrans)

I've only just started learning Python, so I have no idea how efficient this is compared to the other methods, but it works. Also, it doesn't matter whether the text is upper case, lower case or if there is any punctuation etc.

If you want to change all letters:

from string import maketrans

textin = "abcdefghijklmnopqrstuvwxyz"
textout = "cdefghijklmnopqrstuvwxyzab"
texttrans = maketrans(textin, textout)

text = "qcc, gr umpiq"

print text.translate(texttrans)

Also works to change some characters:

from string import maketrans

textin = "81972"
textout = "Seios"
texttrans = maketrans(textin, textout)

text = "811, 9t w7rk2"

print text.translate(texttrans)
Hello爱情风 2024-11-12 21:54:41

这是一个可能对某人有用的包罗万象的方法......

def alphabet(arg, return_lower=True):

    """
        Indexing the english alphabet consisting of 26 letters. 
        Note: zero indexed

            example usage:

                alphabet('a')
                >> 0

                alphabet(25, return_lower=False)
                >> 'Z'

        :param arg: Either type int or type chr specifying the \
                    index of desired letter or ther letter at \
                    the desired index respectivley.
        :param return_lower: If index is passes, returns letter \
                         with corresponding case. Default is \
                         set to True (lower case returned). 
        :returns: integer representing index of passed character \
                    or character at passed index.
    """

    arg = str(arg)
    assert arg.isdigit() or arg.isalpha()

    if arg.isdigit():
        if return_lower:
            return chr(int(arg) + 97).lower()  
        return chr(int(arg) + 97).upper()

    return ord(arg.lower()) - 97

Here's a catch all method that might be useful for someone...

def alphabet(arg, return_lower=True):

    """
        Indexing the english alphabet consisting of 26 letters. 
        Note: zero indexed

            example usage:

                alphabet('a')
                >> 0

                alphabet(25, return_lower=False)
                >> 'Z'

        :param arg: Either type int or type chr specifying the \
                    index of desired letter or ther letter at \
                    the desired index respectivley.
        :param return_lower: If index is passes, returns letter \
                         with corresponding case. Default is \
                         set to True (lower case returned). 
        :returns: integer representing index of passed character \
                    or character at passed index.
    """

    arg = str(arg)
    assert arg.isdigit() or arg.isalpha()

    if arg.isdigit():
        if return_lower:
            return chr(int(arg) + 97).lower()  
        return chr(int(arg) + 97).upper()

    return ord(arg.lower()) - 97
许久 2024-11-12 21:54:41

相当于Excel中的COLUMN函数

def position(word):
    if len(word)>1:
        pos = 0
        for idx, letter in enumerate(word[::-1]):
            pos += (position(letter)+(1 if idx!=0 else 0))*26**(idx)
        return pos
    return ord(word.lower()) - 97


print(position("A")) --> 0
print(position("AA")) --> 26
print(position("AZ")) --> 51

Equivalent of COLUMN function in excel

def position(word):
    if len(word)>1:
        pos = 0
        for idx, letter in enumerate(word[::-1]):
            pos += (position(letter)+(1 if idx!=0 else 0))*26**(idx)
        return pos
    return ord(word.lower()) - 97


print(position("A")) --> 0
print(position("AA")) --> 26
print(position("AZ")) --> 51
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文