从Python中的字符串中除去所有非数字字符(“。”除外)(Strip all non

编程入门 行业动态 更新时间:2024-10-27 22:29:32
从Python中的字符串中除去所有非数字字符(“。”除外)(Strip all non-numeric characters (except for “.”) from a string in Python)

我有一个非常好的工作代码,但我想知道是否有任何更好的建议如何做到这一点:

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'

更多推荐

本文发布于:2023-04-28 09:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   数字   Python   Strip

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!