We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,874 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Picking piece of string between separators

0
By Tony Veijalainen on Jun 12th, 2010 12:48 am

I used this pattern few times to answer a thread and thought to post it as snippet.

# picking up piece of string between separators
## function using partition, like partition
def between(left,right,s):
    before,_,a = s.partition(left)
    a,_,after = a.partition(right)
    return before,a,after

s = "bla bla blaa <a>data</a> lsdjfasdjöf (important notice) 'Daniweb forum' tcha tcha tchaa"
print between('<a>','</a>',s)
print between('(',')',s)
print between("'","'",s)
                     
""" Output:
('bla bla blaa ', 'data', " lsdjfasdj\xc3\xb6f (important notice) 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f ', 'important notice', " 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f (important notice) ', 'Daniweb forum', ' tcha tcha tchaa')
"""

If the left tag is not found, second and third part of tuple are '', all input string is as first part of tuple returned.

If left tag is found but right not, result has after part (third part of tuple) '', and rest of string is all in second part.

pyTony
pyMod
Moderator
6,301 posts since Apr 2010
Reputation Points: 879
Solved Threads: 986
Skill Endorsements: 26

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0592 seconds using 2.69MB