检测Python字符串是数字还是字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40097590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect whether a Python string is a number or a letter
提问by TriskelionKal
How can I detect either numbers or letters in a string? I am aware you use the ASCII codes, but what functions take advantage of them?
如何检测字符串中的数字或字母?我知道您使用 ASCII 代码,但是哪些函数利用了它们?
回答by Moinuddin Quadri
Check if string is positivedigit (integer) and alphabet
检查字符串是否为正数(整数)和字母
You may use str.isdigit()
and str.isalpha()
to check whether given string is positiveinteger and alphabet respectively.
您可以使用str.isdigit()
和str.isalpha()
分别检查给定的字符串是否为正整数和字母。
Sample Results:
示例结果:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
Check for strings as positive/negative - integer/float
检查字符串为正/负 - 整数/浮点数
str.isdigit()
returns False
if the string is a negativenumber or a float number. For example:
str.isdigit()
False
如果字符串是负数或浮点数,则返回。例如:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negativeintegers and float
, then you may write a custom function to check for it as:
如果您还想检查负整数 andfloat
,那么您可以编写一个自定义函数来检查它:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
示例运行:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
Discard "NaN" (not a number) strings while checking for number
检查数字时丢弃“NaN”(不是数字)字符串
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
上述函数将返回True
“NAN”(不是数字)字符串,因为对于 Python 来说,它是表示它不是数字的有效浮点数。例如:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
为了检查数字是否为“NaN”,您可以使用math.isnan()
:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
或者,如果您不想导入额外的库来检查这一点,那么您可以简单地通过使用==
. False
当nan
float 与自身进行比较时Python 返回。例如:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
因此,可以更新上述函数is_number
以返回False
为"NaN"
:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
示例运行:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
Allow Complex Number like "1+2j" to be treated as valid number
允许像“1+2j”这样的复数被视为有效数字
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbersas valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
上面的函数仍然会返回你False
的复数。如果您希望您的is_number
函数将复数视为有效数字,那么您需要将传递的字符串类型转换为complex()
而不是float()
. 然后你的is_number
函数看起来像:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
示例运行:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
PS:根据号码类型,每次检查的每个操作都会带来额外的开销。选择is_number
适合您要求的功能版本。
回答by esquarer
For a string of length 1 you can simply perform isdigit()
or isalpha()
对于长度为 1 的字符串,您可以简单地执行isdigit()
或isalpha()
If your string length is greater than 1, you can make a function something like..
如果您的字符串长度大于 1,您可以创建一个类似..
def isinteger(a):
try:
int(a)
return True
except ValueError:
return False