【问题标题】:How to get character position in alphabet in Python 3.4?如何在 Python 3.4 中获取字母表中的字符位置?
【发布时间】:2016-08-15 23:46:51
【问题描述】:

我需要知道文本中第 n 个字符的字母位置,我阅读了 this questionanswer,但它不适用于我的 Python 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(最近一次调用最后一次):

文件“”,第 1 行,在 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')

文件 "C:\Users\Asus\Desktop\Perso\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", 第 685 行,在运行文件中 execfile(文件名,命名空间)

文件 "C:\Users\Asus\Desktop\Perso\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", 第 85 行,在 execfile 中 exec(compile(open(filename, 'rb').read(), filename, 'exec'), 命名空间)

文件 "C:/Users/Asus/Desktop/Perso/WinPython-64bit-3.4.3.4/python-3.4.3.amd64/Scripts/ESSAI.py", 第 11 行,在 string.lowercase.index('message2')

AttributeError: 'module' 对象没有属性 'lowercase'

【问题讨论】:

    标签: python-3.x alphabet


    【解决方案1】:
    import string
    message='bonjour'
    
    print(string.ascii_lowercase.index(message[2]))
    

    o/p

    13
    

    这对你有用,删除更改索引中的'

    当您提供'' 时,它将被视为一个字符串。

    【讨论】:

    • print(message.lower().index(message[k])) 的答案是 k 我想得到字母排名。所以 message[2] 是 n 并且 n 在字母表中的排名是 14 而不是 2 ... ugh :/
    【解决方案2】:

    你可能正在拍摄类似的东西

    string.ascii_lowercase.index(message[2])
    

    返回 13。你错过了ascii_

    这将起作用(只要消息是小写的),但涉及对字母表的线性搜索,以及模块的导入。

    相反,只需使用

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

    另外,你可以使用

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

    如果message 中的某些字母是大写的,您希望它能够工作。

    如果你想要例如a 的等级为 1 而不是 0,使用

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

    【讨论】:

      猜你喜欢
      • 2011-08-21
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 2012-10-22
      • 2019-12-10
      • 2021-07-16
      相关资源
      最近更新 更多