A preserved archive of the Logical Gamers community forums, 2009-2025. The original threads and posts, served read-only. Registration, posting and private messages are gone for good.

[Python 3.1] stringBetween Function

1.3k views · started by Nat ·
#1
[Python 3.1] stringBetween Function
def stringBetween(stringToSearch, startString, endString):
#stringBetween by Nat + Monarchy for Python 3.1
initPos = stringToSearch.find(startString)
if initPos == '-1':
return ''
else:
initPos = initPos + len(startString)
stringLength = stringToSearch.find(endString, initPos)
return stringToSearch[initPos:stringLength]

#Example usage
x = 'this is my [tag]dog[/tag]'
y = stringBetween(x, "[tag]", "[/tag]")


No idea if anyone will get anything out of this but enjoy. :D
#2
Nice. What happens if you use -1 as the first part of stringToSearch[one:two]?
e.g. stringToSearch[-1:stringLength]
Error? Or does it start at 0 anyway?
#3
What are you even saying? Could be that I'm tired as fuck but that made no sense to me...
#4
x = 'this is my [tag]dog[/tag]'
echo x[-1:len(x)]

I doubt the output function is called echo, but whatever. What is the value of x[-1:len(x)]?
#5
An error probably. Why would you even do that that's in no way relevant?
#6
If it defaulted -1 to 0, then the code could be shorted by quite a bit. Just brainstorming.
#7
If a string is not found then the str.find fuction returns -1.
#8
I know. Which is how it could be shortened.
Something along the lines of:
return x[x.find(start):x.find(end)]
And cut out the middle man that checks to see if it found the string, because if -1 defaults to 0 when taking substrings, then it would just return the entire string (or an empty string, like your program is doing now, if `end` isn't found, 'cause it would return x[-1:-1]).
#9
No it wouldn't it would return the last character in the string...
#10
Alright. That's what I was asking.
#11
K thread over for you at least.