Python 字符串函数

0 投票
4 回答
1176 浏览
提问于 2025-04-18 03:47

我该如何判断一个字符串在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

4 个回答

0

我现在对不同的方法进行了性能测试。is.digit() 的速度快得多,根据你使用它的方式(比如大量循环),使用它可能比自己写一个函数更划算。(顺便提一下,它看起来也更好看。)

如果你想在自己的电脑上运行,可以查看我放在IPython notebook里的内容:

这里是测试结果:

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
0

可以使用 .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
>>> 
2

这个有现成的功能可以用。

'4582'.isdigit() == True
'458dfr'.isdigit() == False

从底层来看,这可能看起来像这样:

def isdigit(self):
    return all(ch in "0123456789" for ch in self)

不过,如果你想把它当作整数来用,那就直接把它当作整数用就行了。

data = "123456"
try:
    data = int(data)
except ValueError:
    # handle this if your data is not a number

不要先去检查某个东西能不能转换,然后再去尝试转换。这个道理适用于把数据转成 int 的情况,也适用于在打开文件之前检查文件是否存在。这样做会产生竞争条件:比如你检查 data 能否转成数字时,它确实可以,但在你转换之前,可能有其他线程把它改了,这样你就会出错。文件也是一样,如果你检查文件存在,但在你打开之前它被删除了,那你就麻烦了。

相反,直接去做你想做的事情,如果出错了再处理错误。这个方法叫做“先做再说”,也就是 Easier to Ask Forgiveness than Permission

5

str对象有一个叫做isdigit的方法,可以帮你完成其中一个任务。从更广的角度来看,直接试一下效果会更好:

def digit(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

举个例子," 1234 ".isdigit()的结果是False(因为有空格),但是Python其实可以把它转换成int类型,所以我的digit函数的结果是True

撰写回答