Python Forum

Full Version: testing if a character in a string is an intended one
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
previously i had asked which was better: word[0] in ('w','x','y','z') vs word[0] in 'wxyz'. but now i have a new variation on the problem. the value for word might be an empty string so i need to change word[0] to word[:1] to avoid an exception i don't want to happen. that means i could be doing the test word[:1] in 'wxyz' with an empty string which would always give a True value for the in operation. so i can't use that one at all and apparently must use word[:1] in ('w','x','y','z') to perform a correct test. the only alternative i can imagine is word[:1] and word[:1] in 'wxyz'.

so, now, between word[:1] in ('w','x','y','z') and word[:1] and word[:1] in 'wxyz' which is the best choice? or is there something even better that i have overlooked?
did u mean bool(word[:1]) and word[:1] in 'wxyz'? else empty string is returned if word is an empty string.i'll say word[:1] in ('w','x','y','z') better in term of efficiency... less keyword/function used
. python 2.7
yes, i meant that. i ass-u-med that and implied bool(). if i had coded that, i would quickly have discovered i was wrong.

looking back at the code which raised this question, it is the conditional of an if statement. so, it would have still worked for that purpose and i would not have learned the point you raised. so, thanks for pointing this out.