如何检查字符串中的特定字符?
我想知道怎么用Python 2来检查一个字符串里是否包含几个特定的字符。
比如,给我这个字符串:
罪犯们偷了$1,000,000的珠宝。
我该怎么判断里面有没有美元符号("$")、逗号(",")和数字呢?
9 个回答
16
这是对Abbafei帖子中提到的时间比较的快速总结:
import timeit
def func1():
phrase = 'Lucky Dog'
return any(i in 'LD' for i in phrase)
def func2():
phrase = 'Lucky Dog'
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
func1_time = timeit.timeit(func1, number=100000)
func2_time = timeit.timeit(func2, number=100000)
print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))
输出结果:
Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371
所以,使用any的代码更简洁,但使用条件判断的速度更快。
编辑: 总结 -- 对于长字符串来说,if-then的速度 仍然 比any快得多!
我决定根据评论中提到的一些有效观点,比较一下长随机字符串的执行时间:
# Tested in Python 2.7.14
import timeit
from string import ascii_letters
from random import choice
def create_random_string(length=1000):
random_list = [choice(ascii_letters) for x in range(length)]
return ''.join(random_list)
def function_using_any(phrase):
return any(i in 'LD' for i in phrase)
def function_using_if_then(phrase):
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
random_string = create_random_string(length=2000)
func1_time = timeit.timeit(stmt="function_using_any(random_string)",
setup="from __main__ import function_using_any, random_string",
number=200000)
func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
setup="from __main__ import function_using_if_then, random_string",
number=200000)
print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))
输出结果:
Time for function using any: 0.1342546
Time for function using if-then: 0.0201827
if-then的速度几乎快了一个数量级,比any快得多!
34
用户 Jochen Ritzel 在回答用户 dappawit 的问题时评论说,这样做应该可以:
('1' in var) and ('2' in var) and ('3' in var) ...
'1', '2' 等等应该替换成你想要查找的字符。
你可以查看 这个 Python 2.7 文档页面,里面有关于字符串的一些信息,包括如何使用 in
操作符来检查子字符串。
更新: 这个方法和我之前的建议效果一样,但重复的部分更少:
# When looking for single characters, this checks for any of the characters...
# ...since strings are collections of characters
any(i in '<string>' for i in '123')
# any(i in 'a' for i in '123') -> False
# any(i in 'b3' for i in '123') -> True
# And when looking for subsrings
any(i in '<string>' for i in ('11','22','33'))
# any(i in 'hello' for i in ('18','36','613')) -> False
# any(i in '613 mitzvahs' for i in ('18','36','613')) ->True
346
假设你的字符串是 s
:
'$' in s # found
'$' not in s # not found
# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found
其他字符也是这样处理的。
...或者
pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found')
else
print('Not found')
...或者
chars = set('0123456789$,')
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')
[编辑:添加了 '$' in s
的答案]