Python Forum
testing if a character in a string is an intended one - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: testing if a character in a string is an intended one (/thread-8562.html)



testing if a character in a string is an intended one - Skaperen - Feb-26-2018

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?


RE: testing if a character in a string is an intended one - ka06059 - Feb-26-2018

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


RE: testing if a character in a string is an intended one - Skaperen - Feb-27-2018

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.