Search for letters in a String [solved]

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • MaxLindquist
    New Member
    • Oct 2006
    • 24

    #1

    Search for letters in a String [solved]

    How do i search for one letter in a String? For example the third letter in Word="Hello". The thought is that i that way can use:

    if (the third letter in Word)=="l":

    Thanks!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by MaxLindquist
    How do i search for one letter in a String? For example the third letter in Word="Hello". The thought is that i that way can use:

    if (the third letter in Word)=="l":

    Thanks!
    Try this:
    Code:
    if string.index(some_string, some_sub_string) == 2:
           .. do_something..

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      I'd say don't forget to import string, BUT 2.4 docs say:
      4.1.4 Deprecated string functions

      index(s, sub[, start[, end]])
      Like find() but raise ValueError when the substring is not found.
      So, use:
      Code:
      someStr.index(subStr)
      but that needs to be wrapped in a try block. So use
      Code:
      index = someStr.find(subStr)
      if index != -1:
      	# do something knowing someStr[index] == subStr if subStr is on character.
      Originally posted by bvdet
      Try this:
      Code:
      if string.index(some_string, some_sub_string) == 2:
      .. do_something..

      Comment

      • Geos
        New Member
        • Oct 2006
        • 2

        #4
        maybe this is just to obvious but if you only want to test the third letter of a string named word try this:

        Code:
        if word[2] == 'l':
        	...

        Comment

        • MaxLindquist
          New Member
          • Oct 2006
          • 24

          #5
          Thanks... hehe... actually it was the most obvious one i was looking for...

          Comment

          Working...