How to get character position in alphabet in Python 3.4?

I need to know the alphabet position of the nth character in the text, and I read the answer of this question , but it does not work with my Python 3.4


My program

# -*- coding: utf-8 -*- """ Created on Fri Apr 22 12:24:15 2016 @author: Asus """ import string message='bonjour' string.lowercase.index('message[2]') 

It does not work with ascii_lowercase instead of a lowercase letter.


Error message

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 (last last call):

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 \ Persian \ WinPython-64bit-3.4.3.4 \ python-3.4.3.amd64 \ Lib \ site-packages \ spyderlib \ Widgets \ externalshell \ sitecustomize.py", line 685, in runfile execfile (file name, namespace)

File "C: \ Users \ Asus \ Desktop \ Persian \ 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 (file name, 'rb'). read (), file name, '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: the 'module' object does not have the 'lowercase' attribute

+5
source share
2 answers
 import string message='bonjour' print(string.ascii_lowercase.index(message[2])) 

o / p

 13 

This will work for you, delete ' in the change index.

When you give, '' then it will be considered a string.

+1
source

You can shoot something like

 string.ascii_lowercase.index(message[2]) 

Which returns 13. You are missing ascii_ .

This will work (as long as the message is lowercase), but it includes a linear alphabetical search, as well as module import.

Instead, just use

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

Alternatively, you can use

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

if you want this to work if some letters in message are uppercase.

If you want, for example, rank a should be 1, not 0, use

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

Source: https://habr.com/ru/post/1247702/


All Articles