2016-04-22 16 views
5

我需要知道在文本中的第n個字符的字母位置,我讀的this questionanswer但它不符合我的Python 3.4如何在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('message 2 ')

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

回答

1
import string 
message='bonjour' 

print(string.ascii_lowercase.index(message[2])) 

O/P

13 

這會爲你工作,在變化指數取出'

當你給''那麼它將被視爲一個字符串。

+0

打印的答案(message.lower()。索引(消息[K]))爲K I想要得到的字母等級。所以消息[2]是n,並且字母n中的n的等級是14不是2 ...呃:/ –

+0

現在它可以工作了,謝謝! :D –

3

你可能會拍攝這樣的事情

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') 
+0

我記住了,謝謝! –

相關問題