python-3.x
  • alphabet
  • 2016-04-22 7 views 5 likes 
    5

    私は、テキスト中のn番目の文字のアルファベットの位置を知る必要があり、私はthis questionanswerを読んで、それは私のPython 3.4Python 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

    を使用し、1ではなく0には、私は、アルファベットのランクを取得したいのkです。だから、メッセージ[2]はnで、アルファベットのnのランクは14ではありません。ugh:/ –

    +0

    これは、ありがとうございます! :D –

    3

    あなたがascii_を欠落していた13を返し

    string.ascii_lowercase.index(message[2]) 
    

    ような何かのために撮影されることがあります。

    これは(メッセージが小文字である限り)動作しますが、アルファベットに対する線形検索とモジュールのインポートを含みます。

    代わりに、単にあなたがmessageで一部の文字が大文字であれば、これは仕事をしたい場合は、

    ord(message[2].lower()) - ord('a') 
    

    を使用することができ、また

    ord(message[2]) - ord('a') 
    

    使用しています。

    aのランクプリント(message.lower()。インデックス(メッセージ[K]))の答え

    1 + ord(message[2].lower()) - ord('a') 
    
    +0

    私はそれを念頭に置いて、ありがとう! –

    関連する問題