【问题标题】:Using translate in Python 2.7在 Python 2.7 中使用翻译
【发布时间】:2019-06-02 02:51:49
【问题描述】:

我有一个带有元音的单词,例如 apple,并且想使用 translate 将元音替换为星号。我正在使用 Python 2.7。

我已经创建了一个翻译表:

import string
table = string.maketrans('*****', 'aeiou')

但是使用它会删除元音而不用星号替换元音:

>> 'apple'.translate(table, 'aeiou')
'ppl'

我已经知道我可以使用其他方法来实现这一点,例如 re:

import re
re.sub('[aeiou]', '*', 'Apple', flags=re.I)

但我想知道是否有办法使用translate

【问题讨论】:

    标签: python python-2.7 translate


    【解决方案1】:

    当然,你需要给它一个适当的映射,允许 __getitem__ 方法按照文档字符串

    maps = {'a': '*', 'e': '*', 'o': '*', 'i': '*', 'u': '*'}
    
    table = str.maketrans(maps)
    
    'apple'.translate(table)
    
    '*ppl*'
    

    既然你现在提到Python 2.7 解决方案,它会是这样的:

    import string
    
    table = string.maketrans('aeoiu', '*****')
    
    'apple'.translate(table)
    '*ppl*'
    

    【讨论】:

    • Python 2.7 打印出TypeError: maketrans() takes exactly 2 arguments (1 given)
    • 我明白了,我的问题是在 translate(), tnx 内提供元音。
    【解决方案2】:

    这可以帮助你:

    table = string.maketrans('aeiou', '*****')
    'apple'.translate(table)
    

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 2017-06-28
      • 2021-09-26
      • 2014-04-22
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2015-09-04
      相关资源
      最近更新 更多