python-3.x - 如何在 Python 3.4 中获取字母表中的字符位置?

标签 python-3.x alphabet

我需要知道文本中第 n 个字符的字母位置,我阅读了 answerthis question但它不适用于我的 Python 3.4

我的程序

# -*- coding: utf-8 -*-
"""
Created on Fri Apr 22 12:24:15 2016

@author: Asus
"""

import string

message='bonjour'
string.lowercase.index('message[2]')

它也不适用于 ascii_lowercase 而不是小写。

错误消息

runfile('C:/Users/Asus/Desktop/Perso/WinPython-64bit-3.4.3.4/python-3.4.3.amd64/Scripts/ESSAI.py', wdir='C:/Users/Asus/Desktop/Perso/WinPython-64bit-3.4.3.4/python-3.4.3.amd64/Scripts') Traceback (most recent call last):

File "", line 1, in runfile('C:/Users/Asus/Desktop/Perso/WinPython-64bit-3.4.3.4/python-3.4.3.amd64/Scripts/ESSAI.py', wdir='C:/Users/Asus/Desktop/Perso/WinPython-64bit-3.4.3.4/python-3.4.3.amd64/Scripts')

File "C:\Users\Asus\Desktop\Perso\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile execfile(filename, namespace)

File "C:\Users\Asus\Desktop\Perso\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

File "C:/Users/Asus/Desktop/Perso/WinPython-64bit-3.4.3.4/python-3.4.3.amd64/Scripts/ESSAI.py", line 11, in string.lowercase.index('message2')

AttributeError: 'module' object has no attribute 'lowercase'

最佳答案

你可能正在拍摄类似的东西

string.ascii_lowercase.index(message[2])

返回 13。你错过了 ascii_ .

这将起作用(只要消息是小写的),但涉及对字母表的线性搜索,以及模块的导入。

相反,只需使用
ord(message[2]) - ord('a')

此外,您可以使用
ord(message[2].lower()) - ord('a')

如果 message 中有一些字母,你想让它工作是大写的。

如果你想要例如排名a为 1 而不是 0,使用
1 + ord(message[2].lower()) - ord('a')

关于python-3.x - 如何在 Python 3.4 中获取字母表中的字符位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36792236/

相关文章:

JavaScript .sort() 到 Python 排序() : How to Convert Callback in JS to key in Python

python - 为什么 Fore.BLUE 使文本以随机字符开头而不是使文本为蓝色?

javascript - 使用 JavaScript 检查字符串是否包含所有字母的最简单代码

javascript - ng-repeat 中带有字母表的项目符号列表

python - 在 python 中迭代 a 到 zzz

c# - 从字母转换为它们在字母表中的相对位置 (c#)

C++ - 按字母顺序排列字符串

Python 3.2 UnicodeEncodeError

python - 为什么 f-strings 在它们引用的变量发生变化时不发生变化?

Python狮身人面像: How to embed code into a docstring?