Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 testing if a character in a string is an intended one
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?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
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
swallow osama bin laden
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.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 207 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  How to get the index of a character from a string chihaya 1 180 Dec-03-2019, 12:54 PM
Last Post: buran
  Conditional not processing as intended (Colt Steele’s Udemy course) Drone4four 3 144 Nov-07-2019, 04:47 PM
Last Post: Drone4four
  python gives wrong string length and wrong character thienson30 2 290 Oct-15-2019, 08:54 PM
Last Post: Gribouillis
  Find string and add character - newbi PyDK 1 318 May-15-2019, 01:22 PM
Last Post: ichabod801
  remove string character from url jacklee26 10 1,323 Mar-25-2019, 03:56 PM
Last Post: Larz60+
  Replace changing string including uppercase character with lowercase character silfer 11 1,118 Mar-25-2019, 12:54 PM
Last Post: silfer
  Changing a character in a string Livne_ye 4 551 Mar-13-2019, 12:39 PM
Last Post: Larz60+
  How Do I find Index of a character in string? ilcaa72 5 959 May-23-2018, 11:44 PM
Last Post: wavic
  find a character in a string in python3 tony1812 6 3,061 Sep-27-2017, 03:28 PM
Last Post: nilamo

Forum Jump:

Users browsing this thread: 1 Guest(s)