258

How can I check if a string has several specific characters in it using Python 2?

For example, given the following string:

The criminals stole 1,000,000ドル in jewels.

How do I detect if it has dollar signs ($), commas (,), and numbers?

Penny Liu
18k5 gold badges89 silver badges109 bronze badges
asked Mar 4, 2011 at 1:47
3
  • 1
    Does that mean every character is supposed to be one of these, or does it suffice that one (or all) of these characters is present in the string? Do they have to be in some order (eg: 2,00ドル) for it be valid? Commented Mar 4, 2011 at 2:11
  • 3
    Just as a different sort of approach, not set(p).isdisjoint(set("0123456789,ドル")) where p is the string to test. Commented May 31, 2015 at 3:51
  • Does this answer your question? Does Python have a string 'contains' substring method? Commented Dec 8, 2021 at 23:47

9 Answers 9

355

Assuming your string is 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')
Toby Speight
32.4k58 gold badges83 silver badges118 bronze badges
answered Mar 4, 2011 at 2:07
Sign up to request clarification or add additional context in comments.

7 Comments

s.find('$')!=-1 => '$' in s :-)
Is there any particular reason why value on not found was kept -1 and not 0 ??
@akki not found is -1 because 0 is the index of the first character in a string. Thus "abc".find('a') = 0. It would be ambiguous if 0 was also the not found value.
I like that last version using any(). Is there a way to refer to the found character c in a pythonic style (it seems to be scoped inside of any() only), or would I need to make the search for several characters more explicit?
The second example is broken: The regex needs to have brackets r'[\d\,ドル]' so it matches any of those characters, and the else: is missing the colon on the end.
|
35

user Jochen Ritzel said this in a comment to an answer to this question from user 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.

See this page in the Python 2.7 documentation for some information on strings, including about using the in operator for substring tests.

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
answered Mar 4, 2011 at 2:39

2 Comments

+1 this is more compact than multiple .find()'s, and is fine as long as the number of characters searched for is low. Doesn't need the parentheses though.
@Sean About the parenthenses: I know, however it is easier for me to always use them, than to always remember the precedence order :-).
16

Quick comparison of timings in response to the post by 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 -- To answer some of the additional comments to my answer (including 2000 spaces in front or changing the syntax of the any statement), if-then is still much faster than any!

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 3.10
import timeit
from string import ascii_letters
from random import choice
def create_random_string_with_2000_spaces_in_front(length=1000):
 random_list = [choice(ascii_letters) for x in range(length)]
 starting_string = ''.join(random_list)
 return ' ' * 2000 + starting_string
def function_using_any(phrase):
 return any(i in 'LD' for i in phrase)
def function_using_modified_any(phrase):
 return any(i in phrase for i in 'LD')
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_with_2000_spaces_in_front(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_modified_any(random_string)",
 setup="from __main__ import function_using_modified_any, random_string",
 number=200000)
 func3_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 modified any: {1}\nTime for function '
 'using if-then: {2}'.format(func1_time, func2_time, func3_time))

Output:

Time for function using any: 24.96421239990741
Time for function using modified any: 0.14611740002874285
Time for function using if-then: 0.03293200000189245

If-then is still almost an order of magnitude faster than any!

answered Jul 14, 2015 at 17:11

5 Comments

Anyone able to explain why the conditional is that much faster than using any?
@Josh probably it's because its simpler. Func1 uses exploded list comprehension so its automatically waaay more complex for simple things. But for 1000 chars, it may well be faster to use Func1
This is very misleading. The performance difference is due to the hit in setting up the generator expression for any(). Increasing the string size to 2000 does almost nothing since it will almost always find an 'L' character within the first 256 characters of a random string. If you were to add 2000 spaces in front the difference would be much less.
The two checks aren't equivalent either. I think the more analogous any statement would be: any(i in phrase for i in 'LD')
@AndrewJesaitis Please see the updated code. If-then is still much faster. Not sure why though.
6

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"
answered Mar 4, 2011 at 2:01

3 Comments

You don't have to escape the $ if it's in a character class. Also this will match 'testing $tring', which I don't think is something the OP wants to happen.
If I recall correctly, it wouldn't match 'testing $tring' it if the match method is used, only if search is used. So I think his code is fine.
@dappa It will still match '$string' though
5

My simple, simple, simple approach! =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!
bad_coder
13.3k20 gold badges60 silver badges95 bronze badges
answered Dec 29, 2020 at 15:27

Comments

1

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]

answered Mar 16, 2021 at 18:19

Comments

0

Another approach, perhaps pythonic, is this:

aString = """The criminals stole 1,000,000ドル in jewels."""
#
if any(list(map(lambda char: char in aString, '0123456789,$')))
 print(True) # Do something.
answered Nov 6, 2022 at 0:12

Comments

0

Replace alphanumerics, spaces, hyphens and full-stops by a blank and then count the number of remaining characters:

import re
s = 'hello%world/'
specialCharacters = re.sub('[a-zA-Z0-9-\s\.()]',','',s)
print( "Special Characters:", specialCharacters )
print( "Length:", len( specialCharacters ) )

and the result is:

Special Characters: $/
Length: 2

and then you can just extend the regular expression if for instance you want to include quotes or questions marks as normal characters.

answered May 4, 2023 at 13:46

Comments

-2
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")
RF1991
2,2634 gold badges13 silver badges20 bronze badges
answered Aug 21, 2018 at 15:36

2 Comments

Could you please provide a bit more context to your answer.
checking type of characters present in a string : isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 ) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z) , isdigit(): Returns True if all characters are digits only( 0 to 9) islower(): Returns True if all characters are lower case alphabet symbols isupper(): Returns True if all characters are upper case aplhabet symbols istitle(): Returns True if string is in title case isspace(): Returns True if string contains only spaces @LazerBass

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.