Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串函数_Python_String_Integer_Boolean_Digit - Fatal编程技术网

Python字符串函数

Python字符串函数,python,string,integer,boolean,digit,Python,String,Integer,Boolean,Digit,在Python中,如何确定字符串是否可以是整数。例如:如果我编写名为digit()和nondigit()的函数。字符串必须是数字(1-9)或字母 str1 = '4582' str1.digit() == True str2 = '458dfr' str2.digit() == False str3 = 'abcd' str3.nondigit() == True str4 = '258edcx' str4.nondigit() == False 有一个内置的 '4582'.isdigit()

在Python中,如何确定字符串是否可以是整数。例如:如果我编写名为digit()和nondigit()的函数。字符串必须是数字(1-9)或字母

str1 = '4582'
str1.digit() == True
str2 = '458dfr'
str2.digit() == False
str3 = 'abcd'
str3.nondigit() == True
str4 = '258edcx'
str4.nondigit() == False

有一个内置的

'4582'.isdigit() == True
'458dfr'.isdigit() == False
“引擎盖下”这可能看起来很像:

def isdigit(self):
    return all(ch in "0123456789" for ch in self)
也就是说,如果你想用它作为int,就用它作为int

data = "123456"
try:
    data = int(data)
except ValueError:
    # handle this if your data is not a number
永远不要测试某个东西,看看它是否能够被转换,然后尝试转换它。这适用于
int
强制转换以及在打开文件之前检查文件是否存在。它创建了一个争用条件,当您检查时,if
data
可以转换为一个数字,但另一个线程接管并在转换为
int
之前将其更改为一个错误。与文件类似,如果您检查该文件是否存在,但在打开它之前有人删除了它,那么您就是SOL


相反,做你想做的事情,如果这会导致错误,“请求原谅”。它是。

str
对象有一个
isdigit
方法来完成您的任务之一。从更广泛的角度来看,最好尝试一下,看看:

def digit(s):
    try:
        int(s)
        return True
    except ValueError:
        return False
例如,
“1234”.isdigit()
False
(有空格),但python可以将其转换为
int
,因此我的
digit
函数是
True

使用
.isdigit()
实现这一功能的内置方法

>>> string = 'hello'
>>> num = '98'
>>> string.isdigit()
False
>>> num.isdigit()
True
>>> 
您还可以创建自己的函数:

>>> def digit(num):
...     try:
...             int(num)
...             return True
...     except ValueError:
...             return False
... 
>>> digit('45')
True
>>> digit('hello')
False
>>> 

我现在对不同的方法进行了基准测试
is.digit()
的速度要快得多,这取决于您对它所做的操作(例如,大型迭代),在自己的函数上使用它可能是有价值的。(顺便说一句,它看起来更漂亮。)

如果您想在您的机器上运行它,我会将其放入:

以下是结果,如果:

import timeit

def string_is_int(a_str):
    try:
        int(a_str)
        return True
    except ValueError:
        return False

an_int = '123'
no_int = '123abc'

%timeit string_is_int(an_int)
%timeit string_is_int(no_int)
%timeit an_int.isdigit()
%timeit no_int.isdigit()

1000000 loops, best of 3: 401 ns per loop
100000 loops, best of 3: 3.04 µs per loop
10000000 loops, best of 3: 92.1 ns per loop
10000000 loops, best of 3: 96.3 ns per loop
此外,我还测试了更一般的情况:

import timeit

def string_is_number(a_str):
    try:
        float(a_str)
        return True
    except ValueError:
        return False

a_float = '1.234'
no_float = '123abc'

a_float.replace('.','',1).isdigit()
no_float.replace('.','',1).isdigit()


%timeit string_is_number(an_int)
%timeit string_is_number(no_int)
%timeit a_float.replace('.','',1).isdigit()
%timeit no_float.replace('.','',1).isdigit()

1000000 loops, best of 3: 400 ns per loop
1000000 loops, best of 3: 1.15 µs per loop
1000000 loops, best of 3: 452 ns per loop
1000000 loops, best of 3: 394 ns per loop

这里有更多解释信息:在解释器中尝试
help(str)
。这些字符串的结果是什么:
['x'、'8'、'-8'、'+8'、'-8'、'+8']
+1,但是请注意
“1234”。strip().isdigit()
将实现相同的目标,而不会引发(相对)昂贵的异常。@That1Guy:OP没有提到这一点,但如果他也希望
“-8”
评估为
,我也不会感到惊讶。另外,不要太担心性能。写清楚的东西,如果太慢,那么进行概要分析和重构。使用
is.digit()
,它更快更“漂亮”,我添加了基准测试作为答案below@SebastianRaschka:注意,OP询问“如何确定字符串在Python中是否可以是整数。”虽然OP将其解释为包含两个函数
digit
notdigit
,但关于字符串是否可以是整数的正确答案是尝试从中生成一个整数,速度更快且“更漂亮”。@StevenRumbalski——我想你的意思是
str.isdigit
,而不是
is.digit
。我提到了
str.isdigit
,但它远没有尝试和捕获异常那么正确。由于它不检查诸如填充空格和前导的
'-'
符号之类的内容,因此它更快也就不足为奇了。。。