1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Pythong string help

Discussion in 'General Programming Chat' started by wickid12, May 1, 2010.

  1. wickid12

    wickid12 Regular Member

    Joined:
    Dec 4, 2009
    Messages:
    363
    Likes Received:
    36
    Does anyone know how to search between two parts in python in a string: like "hey there guy you" I would search for "hey " and "guy" and the result would be there.
     
  2. bigmoneyX

    bigmoneyX Registered Member

    Joined:
    Feb 20, 2008
    Messages:
    99
    Likes Received:
    26
    it's hard to help with out knowing more.

    what do you want it to return? the word between 'hey' and 'guy'? the words 'hey' and 'guy'? etc.
     
  3. wickid12

    wickid12 Regular Member

    Joined:
    Dec 4, 2009
    Messages:
    363
    Likes Received:
    36
    it would return "there".
     
  4. bigmoneyX

    bigmoneyX Registered Member

    Joined:
    Feb 20, 2008
    Messages:
    99
    Likes Received:
    26
    this should get you started

    Code:
    string = "hey there guy you"
    
    # convert string to list
    strlst = string[0:].split(' ')
    
    # convert string to dictionary 
    strdict = dict(enumerate(string[0:].split(' ')))
    
    # find position of words in strlst
    for i in strdict:
    	if strdict[i] == "hey":
    		firstword = i + 1
    	if strdict[i] == "guy":
    		secondword = i
    
    # here's your answer
    
    answer = strlst[firstword:secondword]
    print(answer)
    
    you'll get some strange results if the string has the same word twice (ex: "do you know who you are talking to?")
     
  5. Bartholomew

    Bartholomew Regular Member

    Joined:
    Dec 31, 2009
    Messages:
    290
    Likes Received:
    103
    Home Page:
    Code:
    import re
    s = "hey there guy you hey there are no guy you"
    result = re.findall(r"hey\s(.*?)\sguy", s)
    #result == ["there", "there are no"]