[need help] Python is crashing and stripping charactors

5    23 Jan 2016 18:44 by u/monoxane

So I'm writing an IRC bot and one of the functions replies with a subverse link if it sees 'v/', the problem is it is stripping the last character of the subverse and if there's no words after it it crashes (ie it works it there's ' test v/test test' but crashes at both 'v/test' and 'test v/test') here is the code: ~~~

if data.find('v/') != -1: x = data.split('#')[1] x = x.split('v/')[1] subverse = x.split(' ') subverse[0] = subverse[0].strip(' ' + subverse[1]) subverse = str(subverse[0]) Send(str('voat.co/v/') + subverse) ~~~

Hoping someone can help, if you can, ill pm you the git repo.

2 comments

2

I am not a big fan of Python, (bad experiences with white space dependent languages) but is there a reason you don't use Python's Regular Expression. RegEx is hugely helpful and might help you more easily understand what you were trying to do if you have to come back to it.

Python RegEx

import re
#test data
data = '#test v/test test'
data2 = '#test v/test'
data3 = '#v/test test'
data4 = '#mess up your test!# v/test test'
if data.find('v/') != -1:
 match = re.search('v/(\w*)', data)
 for group in match.groups():
  Send(str('voat.co/v/') + group)
0

Something like this?

def get_subverse_name(data):
    if data.find('v/') != -1:
        words = data.split(' ')
        w = get_sub_word(words)
        trimmed = w.split('v/')
        # trim non valid characters like punctuation before returning.
        # I'm a python noob
        return trimmed[1]
def get_sub_word(words):
    for i in range(0, len(words)):
        word = words[i]
        if word.find('v/') != -1:
            return word
def main():
    tests = ["test v/sub test2",
             "test v/sub",
             "v/sub test",
             "have you seen v/programming? It's dead sometimes."]
    for test in tests:
        output = get_subverse_name(test)
        print("\n#################################################")
        print("\ninput:\n" + test)
        print("\noutput:\n" + output)
        print
if __name__ == '__main__':
    main()

Edit: It could be improved, though. Instead of get_sub_word() returning a single word, it could return a list of words to find every subname instance. You should probably also check if the sub exists.