5

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 not works 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 not works 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 "", 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('message2')

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

Community
  • 1
  • 1
ParaH2
  • 519
  • 1
  • 4
  • 21

2 Answers2

4

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')
John Coleman
  • 51,337
  • 7
  • 54
  • 119
1
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.

backtrack
  • 7,996
  • 5
  • 52
  • 99
  • The answer of print(message.lower().index(message[k])) is k I want to get the alphabet rank. So message[2] is n and the rank of n in alphabet is 14 not 2 ... ugh :/ – ParaH2 Apr 22 '16 at 11:18