ParaH2
ParaH2

Reputation: 517

How to get character position in alphabet in Python 3.4?

I need to know the alphabet position of the n-th character in a text and I read the answer of this question but it does not work with Python 3.4.

My program:

# -*- coding: utf-8 -*-

import string

message = 'bonjour'
string.lowercase.index('message[2]')

It does not work with ascii_lowercase instead of lowercase too.

The 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 (most recent call last):
  File "<ipython-input-14-ba7faba5c581>", line 1, in <module>
    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 <module>
    string.lowercase.index('message[2]')
AttributeError: 'module' object has no attribute 'lowercase'

Upvotes: 5

Views: 7098

Answers (2)

backtrack
backtrack

Reputation: 8144

import string
message='bonjour'

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

o/p

13

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

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

Upvotes: 1

John Coleman
John Coleman

Reputation: 51998

You might be shooting for something like

string.ascii_lowercase.index(message[2])

Which returns 13. You were missing ascii_.

This will work (as long as the message is lower case) but involves a linear search over the alphabet, as well as the importing of a module.

Instead, simply use

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

Also, you could use

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

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

If you want the e.g. the rank of a to be 1 rather than 0, use

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

Upvotes: 4

Related Questions