字符串替换
2016-11-30 09:58
232 查看
题目: 给定一个英文的字符串, 要求你将其中的元音删除掉, 返回新的字符串.
例如:
"This website is for losers LOL!" --> "Ths wbst s fr lsrs LL!"
当看到这个题目的时候, 第一个想起的就是re模块的正则表达式. 不过由于最近使用过字符串的replace方法, 所以我给出的解决方法是:
这样就可以不用使用re模块就完成了要求. 但是, 还有人给出了更精妙的解决方案:
还有许多其他的解决方案, 有兴趣的可以访问:
https://www.codewars.com/kata/disemvowel-trolls/solutions/python/all/best_practice
这里使用了一个字符串特别的方法, translate. 而这个方法平时我都没怎么注意过, 下面是官方文档的说明:
返回一个字符串的副本, 所以出现在可选参数deletechars中的字符将会被移除, 而剩余的的字符将会通过给定的转化表进行映射替换, 这个表必须是长度256的字符串或者是None. 当为None时就不进行映射替换.
所以 s.translate(None, "aeiouAEIOU") 的意思就是删除掉特定的字符了.
而关于映射表的使用, 一般要借用string模块, 下面是一个示例:
结果:
按照方法的定义, 首先去除对应的字符, a和g在映射替换前其实已经被去掉了, 所以在进行映射替换的时候, a是不存在的, 所以并没有映射替换成1, 结果也就如上所示了.
中文意义如何?
结果:
结论: 中文无意义, 不过一般来说, 做日志分析之类的工作时, 面对的多数是英文, 此时作用还是很大的.
例如:
"This website is for losers LOL!" --> "Ths wbst s fr lsrs LL!"
当看到这个题目的时候, 第一个想起的就是re模块的正则表达式. 不过由于最近使用过字符串的replace方法, 所以我给出的解决方法是:
def disemvowel(string): remove_list = ["A", "a", "E", "e", "I", "i", "O", "o", "U", "u"] # 先列出元音列表 for s in remove_list: while s in string: string = string.replace(s, "") # 将元音字符替换为空再重新赋值回去 return string
这样就可以不用使用re模块就完成了要求. 但是, 还有人给出了更精妙的解决方案:
def disemvowel(s): return s.translate(None, "aeiouAEIOU")
还有许多其他的解决方案, 有兴趣的可以访问:
https://www.codewars.com/kata/disemvowel-trolls/solutions/python/all/best_practice
这里使用了一个字符串特别的方法, translate. 而这个方法平时我都没怎么注意过, 下面是官方文档的说明:
S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars.
返回一个字符串的副本, 所以出现在可选参数deletechars中的字符将会被移除, 而剩余的的字符将会通过给定的转化表进行映射替换, 这个表必须是长度256的字符串或者是None. 当为None时就不进行映射替换.
所以 s.translate(None, "aeiouAEIOU") 的意思就是删除掉特定的字符了.
而关于映射表的使用, 一般要借用string模块, 下面是一个示例:
from string import maketrans in_str = "abc" out_str = "123" table = maketrans(in_str, out_str) raw_str = "abc def ghi" result = raw_str.translate(table, "ag") print result
结果:
按照方法的定义, 首先去除对应的字符, a和g在映射替换前其实已经被去掉了, 所以在进行映射替换的时候, a是不存在的, 所以并没有映射替换成1, 结果也就如上所示了.
中文意义如何?
#!/usr/bin/env python # coding: utf-8 from string import maketrans in_str = "好" out_str = "坏" table = maketrans(in_str, out_str) raw_str = "你好" result = raw_str.translate(table) print result
结果:
结论: 中文无意义, 不过一般来说, 做日志分析之类的工作时, 面对的多数是英文, 此时作用还是很大的.
相关文章推荐
- js的replace如何全部替换目标字符串
- 字符串拷贝并替换\0
- Linux中使用sed命令替换字符串小结(转)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 )
- linux sed 批量替换字符串
- 分析字符串替换的高效方法
- js使用Replace结合正则替换重复出现的字符串功能示例
- 字符串---空格替换
- 更改sql多条数据,更新替换字符串中固定的字符串
- python字符串之查找与替换
- 1.5 字符串内容替换
- 字符串空值替换
- 替换字符串中所有子串
- TextView中使用一个字符串替换字符串str中start到end的子字符串
- string替换所有指定字符串(C++)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- js字符串替换
- python字符串替换示例
- Linux下快速替换文本中的字符串