我有一个非常好的工作代码,但我想知道是否有任何更好的建议如何做到这一点:
val = ''.join([c for c in val if c in '1234567890.'])你会怎么做?
I've got a pretty good working snippit of code, but I was wondering if anyone has any better suggestions on how to do this:
val = ''.join([c for c in val if c in '1234567890.'])What would you do?
最满意答案
您可以使用正则表达式(使用re模块)来完成相同的事情。 下面的示例匹配运行的[^\d.] (任何不是十进制数字或句点的字符),并用空字符串替换它们。 请注意,如果使用UNICODE标志编译模式,则生成的字符串仍可能包含非ASCII数字 。 此外,删除“非数字”字符后的结果不一定是有效的数字。
>>> import re >>> non_decimal = re.compile(r'[^\d.]+') >>> non_decimal.sub('', '12.34fe4e') '12.344'You can use a regular expression (using the re module) to accomplish the same thing. The example below matches runs of [^\d.] (any character that's not a decimal digit or a period) and replaces them with the empty string. Note that if the pattern is compiled with the UNICODE flag the resulting string could still include non-ASCII numbers. Also, the result after removing "non-numeric" characters is not necessarily a valid number.
>>> import re >>> non_decimal = re.compile(r'[^\d.]+') >>> non_decimal.sub('', '12.34fe4e') '12.344'更多推荐
发布评论