2008-08-22

[HowTo] Python's substring of a string workaround

In Python there is no dedicated function like "substring" (there is such a function in C#). In the following I have marked a workaround that retrieves the substring (the encoding in this particular case) of a super string that comes after "=" (equal sign):

def fetchContent(self, url): try: fetchResult = urlfetch.fetch(url) except: return 'Exception: Not an URL' if fetchResult.status_code == 200: encTypeRaw = fetchResult.headers['content-type'] encStartIdx = encTypeRaw.find('=') encType = encTypeRaw[encStartIdx + 1:] fetchResultContent = fetchResult.content return fetchResultContent.decode(encType) return 'Warning: URL could not be retrieved successfully'