我需要知道文本中第 n 个字符的字母位置,我阅读了 answer的 this 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/