Codewars 刷题笔记(Python)5.Disemvowel Trolls

2023-05-16

题目

Trolls are attacking your comment section!

A common way to deal with this situation is to remove all of the vowels from the trolls’ comments, neutralizing the threat.

Your task is to write a function that takes a string and return a new string with all vowels removed.

For example, the string “This website is for losers LOL!” would become “Ths wbst s fr lsrs LL!”.

Note: for this kata y isn’t considered a vowel.

难度:7 kyu

题目简述

入参:字符串

功能:移除字符串中所有的元音字母,返回结果字符串

我的解法1

def disemvowel(string):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    result = []
    for s in string:
        if s not in vowels:
            result.append(s)    
    return "".join(result)

写完后自己觉得太长,根据之前的经验,试着用列表生成式的方式简化代码,得到解法2.

我的解法2

def disemvowel(string):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    return "".join([s for s in string if s not in vowels])

用列表生成式简化了下代码

更优解法1

def disemvowel(s):
    return s.translate(None, "aeiouAEIOU")

Python translate()方法

translate()语法:

str.translate(table[, deletechars]);

参数

  • table – 翻译表,翻译表是通过maketrans方法转换而来。
  • deletechars – 字符串中要过滤的字符列表。

这里我们只需删除字符,而无需进行任何的字符转换,所以将table置为None,只指定要过滤的字符列表。

更优解法2

def disemvowel(string):
    return "".join(c for c in string if c.lower() not in "aeiou")

这里用的是生成器表达式而非列表生成式,对于前者了解不多,暂记。

学习总结

  1. Python删除字符串中多个特定字符,较为便捷的方式:s.translate(None, "过滤字符列表"),强烈推荐!
  2. 字符串和列表一样,都能直接进行成员判断,不用新建列表,多此一举
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Codewars 刷题笔记(Python)5.Disemvowel Trolls 的相关文章

随机推荐