Search code examples
pythonstringhashtag

Finding words that start with character will fail with new line


I am trying to write a program that highlights hashtags in tweets. but the program will fail if the tweet contains a new line, the program will work if it is just one line. Why is it failing when there is a new line in the data? I get the error index out of range.

def highlight(data):
    for word in data.split(" "):
        if word[0] == "#":
            print "<FONT COLOR=\"brown\">" + word + "</FONT>",
        else:
            print word,

highlight("""hello world this
    is a #test that i am #writing.""")

Solution

  • This code will work:

    def highlight(data):
        for word in data.split():
            if word[0] == "#":
                print "<FONT COLOR=\"brown\">" + word + "</FONT>",
            else:
                print word,
    
    highlight("""hello world this
        is a #test that i am #writing.""")
    

    This will split the text up by newlines and by whitespace.