Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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'

like image 757
ParaH2 Avatar asked Apr 22 '16 11:04

ParaH2


2 Answers

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')
like image 139
John Coleman Avatar answered Nov 15 '22 08:11

John Coleman


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.

like image 24
backtrack Avatar answered Nov 15 '22 07:11

backtrack