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

时间:2011-03-04 01:47:25

标签: python string

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

7 个答案:

答案 0 :(得分:230)

假设您的字符串为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 :(得分:20)

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

('1' in var) and ('2' in var) and ('3' in var) ...

'1','2'等应替换为您要查找的字符。

有关字符串的一些信息,请参阅this page in the Python 2.7 documentation,包括使用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 :(得分:7)

快速比较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

所以代码对任何代码都更紧凑,但条件更快。

答案 3 :(得分:3)

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

import re

s1 = 'Testing string'
s2 = '1234,12345$'

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

if ( regex.match(s1) ):
   print "s1 matched"
else:
   print "s1 didn't match"

if ( regex.match(s2) ):
   print "s2 matched"
else:
   print "s2 didn't match"

答案 4 :(得分:0)

我的简单,简单,简单的方法! =D

代码

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!

谢谢!

答案 5 :(得分:0)

检查字符是否在字符串中:

parse_string = lambda chars, string: [char in string for char in chars]

示例:

parse_string('axl', 'hello') 

parse_string(['a', 'x', 'l'], 'hello')
<块引用>

输出:[False, False, True]

答案 6 :(得分:-1)

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")   

其他:
     打印(“非太空特殊字符”)