在 Python 中检查字符串中的数字

发布于 2024-11-27 19:10:54 字数 84 浏览 0 评论 0原文

如何在Python中检查字符串是否包含数字?

我有一个要转换为浮点数的变量,但我想制作 if 语句,仅当它仅包含数字时才将其转换为浮点数。

How to check if string contains numbers in Python?

I have a variable which I am convert to float, but I want to make if statement, to convert it to float only if it contains only numbers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

爱她像谁 2024-12-04 19:10:54

只需转换它并在失败时捕获异常即可。

s = "3.14"
try:
  val = float(s)
except ValueError:
  val = None

Just convert it and catch the exception if it fails.

s = "3.14"
try:
  val = float(s)
except ValueError:
  val = None
鹤仙姿 2024-12-04 19:10:54

我会使用 try- except 块来确定它是否是一个数字。这样,如果 s 是一个数字,则转换成功,如果不是,您将捕获 ValueError,这样您的程序就不会中断。

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

I would use a try-except block to determine if it is a number. That way if s is a number the cast is successful, and if it isn't you catch the ValueError so your program doesn't break.

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
宁愿没拥抱 2024-12-04 19:10:54

您还可以从字符串中提取数字。

import string
extract_digits = lambda x: "".join(char for char in x if char in string.digits + ".")

然后将它们转换为浮点数。

to_float = lambda x: float(x) if x.count(".") <= 1 else None

>>> token = "My pants got 2.5 legs"
>>> extract_digits(token)
'2.5'
>>> to_float(_)
2.5
>>> token = "this is not a valid number: 2.5.52"
>>> extract_digits(token)
'2.5.52'
>>> to_float(_)
None

You could also extract numbers from a string.

import string
extract_digits = lambda x: "".join(char for char in x if char in string.digits + ".")

and then convert them to float.

to_float = lambda x: float(x) if x.count(".") <= 1 else None

>>> token = "My pants got 2.5 legs"
>>> extract_digits(token)
'2.5'
>>> to_float(_)
2.5
>>> token = "this is not a valid number: 2.5.52"
>>> extract_digits(token)
'2.5.52'
>>> to_float(_)
None
香草可樂 2024-12-04 19:10:54

为什么不使用内置的 .isdigit() 来实现此目的。紧凑、无 try 语句且速度超快:

string = float(string) if string.isdigit() else string

在考虑 Python 中的错误处理时,我相信尤达大师曾说过:“没有 try。做或不做。”

Why not the built-in .isdigit() for this. Compact, no try statements, and super fast:

string = float(string) if string.isdigit() else string

When considering error handling in Python, I believe it was Master Yoda who said, "There is no try. Do or do not."

已下线请稍等 2024-12-04 19:10:54

迈克尔·巴伯的答案对于速度来说是最好的,因为没有不必要的逻辑。如果由于某种原因您发现需要进行更精细的评估,您可以使用 Python 标准库的正则表达式模块。例如,如果您决定想要获得您所描述的数字,但有想要分层的其他标准,这将对您有所帮助。

import re
mystring = '.0323asdffa'

def find_number_with_or_without_decimal(mystring):
    return re.findall(r"^\.?\d+", mystring)

In [1]: find_number_with_or_without_decimal(mystring)
Out[1]: ['.0323']

正则表达式表示,'查找最多以一位小数开头的内容('^' 表示仅在行开头,'?' 表示最多一位;小数点用 '\' 转义,因此不会有其特殊的正则表达式含义为“任何字符”)并且具有任意数量的数字。祝 Python 好运!

Michael Barber's answer will be best for speed since there's no unnecessary logic. If for some reason you find you need to make a more granular assessment, you could use the Python standard library's regular expression module. This would help you if you decided, for example, that you wanted to get a number like you described but had additional criteria you wanted to layer on.

import re
mystring = '.0323asdffa'

def find_number_with_or_without_decimal(mystring):
    return re.findall(r"^\.?\d+", mystring)

In [1]: find_number_with_or_without_decimal(mystring)
Out[1]: ['.0323']

The regular expression says, 'find something that starts with up to one decimal ('^' means only at beginning of line and the '?' means up to one; the decimal is escaped with a '\' so it won't have its special regular expression meaning of 'any character') and has any number of digits. Good luck with Python!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文