简体   繁体   English

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

[英]How to check a string for specific characters?

How can I check if a string has several specific characters in it using Python 2?如何使用 Python 2 检查字符串中是否包含多个特定字符?

For example, given the following string:例如,给定以下字符串:

The criminals stole $1,000,000 in jewels.犯罪分子偷走了价值 1,000,000 美元的珠宝。

How do I detect if it has dollar signs ("$"), commas (","), and numbers?如何检测它是否有美元符号 ("$")、逗号 (",") 和数字?

Assuming your string is s :假设你的字符串是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

And so on for other characters.其他角色依此类推。

... or ... 或者

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

... or ... 或者

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

[Edit: added the '$' in s answers] [编辑: '$' in s答案中添加了'$' in s ]

user Jochen Ritzel said this in a comment to an answer to this question from user dappawit.用户 Jochen Ritzel 在评论用户 dappawit 对此问题的回答时说到。 It should work:它应该工作:

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

'1', '2', etc. should be replaced with the characters you are looking for. '1'、'2' 等应替换为您要查找的字符。

See this page in the Python 2.7 documentation for some information on strings, including about using the in operator for substring tests.有关字符串的一些信息,包括有关使用in运算符进行子字符串测试的信息,请参阅Python 2.7 文档中的此页面

Update: This does the same job as my above suggestion with less repetition:更新:这与我上面的建议做同样的工作,但重复次数更少:

# 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

Quick comparison of timings in response to the post by Abbafei:响应 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))

Output:输出:

Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371

So the code is more compact with any, but faster with the conditional.所以代码更紧凑,但条件更快。


EDIT : TL;DR -- For long strings, if-then is still much faster than any!编辑: TL;DR-对于长字符串,if-then仍然比任何字符串都快!

I decided to compare the timing for a long random string based on some of the valid points raised in the comments:我决定根据评论中提出的一些有效观点来比较长随机字符串的时间:

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

Output:输出:

Time for function using any: 0.1342546
Time for function using if-then: 0.0201827

If-then is almost an order of magnitude faster than any!如果-那么几乎比任何一个都快一个数量级!

This will test if strings are made up of some combination or digits, the dollar sign, and a commas.这将测试字符串是否由某些组合或数字、美元符号和逗号组成。 Is that what you're looking for?这就是你要找的吗?

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"

My simple, simple, simple approach!我的简单,简单,简单的方法! =D =D

Code代码

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

Output输出

Char "$" detected!
Char "," detected!
Char "0" detected!
Char "1" detected!

Thanks!谢谢!

Check if chars are in String:检查字符是否在字符串中:

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

example:例子:

parse_string('$,x', 'The criminals stole $1,000,000 in ....') 

or或者

parse_string(['$', ',', 'x'], '..minals stole $1,000,000 i..')

output: [True, True, False]输出: [True, True, False]

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

else:别的:
print("Non Space Special Character") print("非空格特殊字符")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM