我需要知道文本中第 n 个字符的字母位置,我阅读了这个问题的答案,但它不适用于我的 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') 回溯(最近一次调用):
文件 ",第 1 行,在 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')
文件 "C:\Users\Asus\Desktop\Perso\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", 第 685 行,在运行文件中 可执行文件(文件名,命名空间)
文件 "C:\Users\Asus\Desktop\Perso\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", 第 85 行,在执行文件中 exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
文件 "C:/Users/Asus/Desktop/Perso/WinPython-64bit-3.4.3.4/python-3.4.3.amd64/Scripts/ESSAI.py", 第 11 行,在 string.lowercase.index('message2')
属性错误:"模块"对象没有属性"小写"
您可能正在拍摄类似的东西
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')
import string
message='bonjour'
print(string.ascii_lowercase.index(message[2]))
o/p
13
这将对您有用,删除更改索引中的'
。
当你给出''
时,它将被视为一个字符串。