如何用相应的数字替换字符串中的字母?

时间:2017-06-01 19:36:07

标签: python

我使用Python 3,我想知道如何用字母表中的相应位置替换单个字母。该功能应忽略任何非英文字母的字符。

所以,输入:

def replaceWithNumber("hello")

该函数将返回:

"8 5 12 12 15"

有关:

def replaceWithNumber("Hissy93")

输出结果为:

"12 9 19 19"

我之前没有问过这个具体的问题,并且想知道最快的方法是什么?

2 个答案:

答案 0 :(得分:1)

def replace_with_number (word):
    return ' '.join(str(ord(x) - 96) for x in word.lower() if 'a' <= x <= 'z')

用例:

>>> replace_with_number('Hello, World!')
'8 5 12 12 15 23 15 18 12 4'
>>> replace_with_number('StackOverflow')
'19 20 1 3 11 15 22 5 18 6 12 15 23'

答案 1 :(得分:0)

>>> def replace_with_number(str):
...     return [ord(x) - ord('a') + 1 for x in str]
... 
>>> replace_with_number(str)
[8, 5, 12, 12, 15]
>>> 
相关问题