问题:如何检查字符串中的特定字符?[关闭]
如何使用Python 2检查字符串中是否包含几个特定字符?
例如,给定以下字符串:
罪犯偷走了1,000,000美元的珠宝。
如何检测它是否带有美元符号(“ $”),逗号(“,”)和数字?
回答 0
假设您的字符串是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
答案]
回答 1
用户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
回答 2
快速比较时间,以回应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
因此,任何代码都更紧凑,而条件代码则更快。
编辑: 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
如果-那么几乎比任何一个都快一个数量级!
回答 3
这将测试字符串是否由某些组合或数字,美元符号和逗号组成。那是您要找的东西吗?
汇入 s1 ='测试字符串' s2 ='1234,12345 $' regex = re.compile('[0-9,$] + $') 如果(regex.match(s1)): 打印“ s1匹配” 其他: 打印“ s1不匹配” 如果(regex.match(s2)): 打印“ s2匹配” 其他: 打印“ s2不匹配”
回答 4
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
否则:
print(“非空间特殊字符”)