How do you check if a string contains a particular character in python?
How can I check if a string has several specific characters in it using Python 2? For example, given the following string:
How do I detect if it has dollar signs ("$"), commas (","), and numbers?
Jesuisme 1,6351 gold badge31 silver badges39 bronze badges
asked Mar 4, 2011 at 1:47
3 Assuming your string is
And so on for other characters. ... or
... or
[Edit: added the answered Mar 4, 2011 at 2:07
dappawitdappawit 11.7k2 gold badges31 silver badges26 bronze badges 7 user Jochen Ritzel said this in a comment to an answer to this question from user dappawit. It should work:
'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 Update: This does the same job as my above suggestion with less repetition:
answered Mar 4, 2011 at 2:39
AbbafeiAbbafei 3,0183 gold badges26 silver badges24 bronze badges 2 Quick comparison of timings in response to the post by Abbafei:
Output:
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! I decided to compare the timing for a long random string based on some of the valid points raised in the comments:
Output:
If-then is almost an order of magnitude faster than any! answered Jul 14, 2015 at 17:11
JesuismeJesuisme 1,6351 gold badge31 silver badges39 bronze badges 3 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
ajwoodajwood 17.2k15 gold badges58 silver badges100 bronze badges 3 Check if chars are in String:
example:
or
answered Mar 16, 2021 at 18:19
FelixFelix 112 bronze badges My simple, simple, simple approach! =D Code
Output
bad_coder 9,28119 gold badges37 silver badges61 bronze badges answered Dec 29, 2020 at 15:27
Eduardo LucioEduardo Lucio 1,2551 gold badge19 silver badges33 bronze badges
else: answered Aug 21, 2018 at 15:36
NagarajNagaraj 5682 gold badges5 silver badges8 bronze badges 2 |