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

The*_*Woo 162 python string

如何使用Python2检查字符串值是否包含确切的字符?具体来说,我希望检测它是否有美元符号("$"),逗号(",")和数字.

dap*_*wit 243

假设你的字符串是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
Run Code Online (Sandbox Code Playgroud)

等等其他角色.

... 要么

pattern = re.compile(r'\d\$,')
if pattern.findall(s):
    print('Found')
else
    print('Not found')
Run Code Online (Sandbox Code Playgroud)

... 要么

chars = set('0123456789$,')
if any((c in chars) for c in s):
    print('Found')
else:
    print('Not Found')
Run Code Online (Sandbox Code Playgroud)

[编辑:添加'$' in s答案]

  • `s.find('$')!= - 1` =>`'''s s` :-) (19认同)
  • 第二个例子被破坏了:正则表达式需要括号`r'[\ d\$,]'`所以它匹配任何这些字符,而`else:`在结尾处缺少冒号. (3认同)
  • @akki not found 是 -1,因为 0 是字符串中第一个字符的索引。因此,“abc”.find('a') = 0。如果 0 也是未找到的值,那将是模棱两可的。 (2认同)

Abb*_*fei 20

用户Jochen Ritzel在评论用户dappawit回答这个问题时说.它应该工作:

('1' in var) and ('2' in var) and ('3' in var) ...
Run Code Online (Sandbox Code Playgroud)

'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
Run Code Online (Sandbox Code Playgroud)


Jes*_*sme 8

阿巴菲回应帖子的时间快速比较:

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))
Run Code Online (Sandbox Code Playgroud)

输出:

Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371
Run Code Online (Sandbox Code Playgroud)

所以代码在任何情况下都更紧凑,但条件更快.


ajw*_*ood 6

这将测试字符串是否由某些组合或数字、美元符号和逗号组成。这就是你要找的吗?

进口重新

s1 = '测试字符串'
s2 = '1234,12345$'

regex = re.compile('[0-9,$]+$')

如果(正则表达式。匹配(s1)):
   打印“s1 匹配”
别的:
   打印“s1 不匹配”

如果(正则表达式。匹配(s2)):
   打印“s2匹配”
别的:
   打印“s2 不匹配”