如何检查特定字符的string?
如何使用Python2检查string值是否包含确切的字符? 具体来说,我期待检测是否有美元符号(“$”),逗号(“,”)和数字。
假设你的string是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
答案中添加'$' in s
]
用户Jochen Ritzel在对用户dappawit回答这个问题的评论中这样说。 它应该工作:
('1' in var) and ('2' in var) and ('3' in var) ...
应将“1”,“2”等replace为您要查找的字符。
有关string的一些信息,请参阅Python 2.7文档中的此页面 ,包括有关使用in
运算符进行子stringtesting的信息。
更新:这与我的上面的build议重复较less的工作相同:
# 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
Abbafei回复post时间的快速比较:
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
所以代码更紧凑,但条件更快。
这将testingstring是否由一些组合或数字,美元符号和逗号组成。 那是你在找什么?
导入重新 s1 ='testingstring' s2 ='1234,12345 $' regex = re.compile('[0-9,$] + $') if(regex.match(s1)): 打印“s1匹配” 其他: 打印“s1不匹配” if(regex.match(s2)): 打印“s2匹配” 其他: 打印“s2不匹配”
sWord = "pizza and chips" for i in range(0, len(sWord)): print(sWord[i]) if sWord[i]=="d": print("Found ad")