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

2024-05-16 08:53:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python3,我想知道如何用字母表中相应的位置替换单个字母。函数应该忽略任何非英文字母的字符。你知道吗

因此,对于输入:

def replaceWithNumber("hello")

函数将返回:

"8 5 12 12 15"

用于:

def replaceWithNumber("Hissy93")

输出为:

"12 9 19 19"

我不知道以前有人问过这个问题,我想知道最快的方法是什么?你知道吗


Tags: 方法函数hellodef字母字符字母表python3
2条回答
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'
>>> def replace_with_number(str):
...     return [ord(x) - ord('a') + 1 for x in str]
... 
>>> replace_with_number(str)
[8, 5, 12, 12, 15]
>>> 

相关问题 更多 >