如何检查字符串中的特定字符?

如何使用Python2检查字符串值中是否包含确切的字符?具体来说,我正在寻找是否有美元符号(“ $”),逗号(“,”)和数字。



慕尼黑5688855
浏览 608回答 3
3回答

摇曳的蔷薇

假设您的字符串是s:'$' in s        # found'$' not in s    # not found# original answer given, but less Pythonic than the above...s.find('$')==-1 # not founds.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')

大话西游666

它应该工作:('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 charactersany(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 subsringsany(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

眼眸繁星

import timeitdef 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 Falseif __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.0737484362111Func2 Time: 0.0125144964371因此,任何代码都更紧凑,而条件代码则更快。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python