我如何检查一个字符串是否有几个特定的字符在它使用Python 2?
例如,给定以下字符串:
罪犯们偷了价值一百万美元的珠宝。
我如何检测它是否有美元符号(“$”),逗号(“,”)和数字?
我如何检查一个字符串是否有几个特定的字符在它使用Python 2?
例如,给定以下字符串:
罪犯们偷了价值一百万美元的珠宝。
我如何检测它是否有美元符号(“$”),逗号(“,”)和数字?
当前回答
另一种可能是python式的方法是:
aString = """The criminals stole $1,000,000 in jewels."""
#
if any(list(map(lambda char: char in aString, '0123456789,$')))
print(True) # Do something.
其他回答
假设你的字符串是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')
[编辑:在s的答案中增加了'$']
另一种可能是python式的方法是:
aString = """The criminals stole $1,000,000 in jewels."""
#
if any(list(map(lambda char: char in aString, '0123456789,$')))
print(True) # Do something.
对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时代码更紧凑,但使用条件时速度更快。
编辑:TL;DR—对于长字符串,if-then仍然比任何快得多!
我决定根据评论中提出的一些有效点来比较一个长随机字符串的计时:
# 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几乎比任何一个数量级都快!
检查字符串中是否有字符:
parse_string = lambda chars, string: [char in string for char in chars]
例子:
parse_string('$,x', 'The criminals stole $1,000,000 in ....')
or
parse_string(['$', ',', 'x'], '..minals stole $1,000,000 i..')
输出:[True, True, False]
我的简单,简单,简单的方法!= D
Code
string_to_test = "The criminals stole $1,000,000 in jewels."
chars_to_check = ["$", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in chars_to_check:
if char in string_to_test:
print("Char \"" + char + "\" detected!")
输出
Char "$" detected!
Char "," detected!
Char "0" detected!
Char "1" detected!