how to retrieve strings from within strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Yudesh
    New Member
    • Mar 2008
    • 6

    how to retrieve strings from within strings

    Hi

    I need to ask something

    I am trying to retrieve a value from a string and I have noticed the following:

    Scenario:
    - I have retrieved lines from a file and need to read each line to retreive a certain string from the line i.e.
    LINE = "THISISATES T"
    I would need to retrieve the work TEST for processing.

    I have noticed that when I declare string - and then parse for the value like string[8:4] it gives me a blank, but when I say string[8:len(string)], I get a value.

    The problem comes in when I am trying to retrieve a value before the end of the string i.e. If I had to get the value ISA.

    How do I do it, because using the string[0:0] format does not work - or does it?

    Am I using it incorrectly?

    Should I be using something like the find/ rfind command?

    Thanks
    Yudesh
  • bgeddy
    New Member
    • Aug 2007
    • 16

    #2
    You're using slicing incorrectly. The format is string[X:Y:Z] where X=start position (starts from 0), Y=non inclusive end position and Z=step.

    So :
    string="THISISA TESTISNTIT"
    string[7:11]="TEST

    Check out slicing in the docs..

    You could use :

    if "TEST" in string:

    to just test for the existence of "TEST" in the string.

    Comment

    • jlm699
      Contributor
      • Jul 2007
      • 314

      #3
      [CODE=python]
      >>> srch = 'isa'
      >>> st = 'thisisateststr ing'
      >>> st[st.find(srch):s t.find(srch)+le n(srch)]
      'isa'
      >>>
      [/CODE]

      Using a combination of find and the slicing will enable you to have a little more flexibility with your code

      Comment

      • Yudesh
        New Member
        • Mar 2008
        • 6

        #4
        Thanks for the info guys - I will put it to good use

        Comment

        Working...