Wednesday, December 3, 2014

1.3.5 Activity response: Strings

So recently I was asked to make a "Tweet verifier" in Python for a fictional "inspirational quote" contest. The Tweet needs to be 140 characters or less and needs a comma, a quote, a question mark and an exclamation mark.

The code:

from __future__ import print_function
def CheckTweet(Tweet):
    com = ',' in Tweet
    quo = '"' in Tweet
    que = "?" in Tweet #These are true of the character is in the tweet.
    exc = "!" in Tweet
    length = len(Tweet)<=140 #This is false if the tweet is over 140 characters.
    over = str(len(Tweet)-140) #Store how many characters the tweet is over the limit.
    errors = []
    if not com:
        errors.append("a comma") #Put what's missing in proper english in a list.
    if not quo:
        errors.append("a quote")
    if not que:
        errors.append("a question")
    if not exc:
        errors.append("an exclamation mark")
    if com and quo and exc and que: #If nothing is missing...
        if length:
            return "Tweet verified. You're good to go!" #AND if it's short enough.
        else:
            return "Sorry, but your Tweet is " + over + " characters over the limit (140)." 
    else:
        msg = "Sorry, but your tweet needs " #Starting off the 'missing stuff' message
        
        if len(errors)==1: #Add commas, periods and 'and's between what's missing to make proper english!
            msg = msg + errors[0] + "."
        elif len(errors)==2:
            msg = msg + errors[0] + " and " + errors[1] + "."
        elif len(errors)==3:
            msg = msg + errors[0] + ", " + errors[1] + " and " + errors[2] + "."
        else:
            msg = msg + errors[0] + ", " + errors[1] + ", " + errors[2] + " and " + errors[3] + "."
        if not length: #If you're ALSO over the limit, add this in a second line.
            msg = msg + "\nAdditionally, your Tweet is " + over + " characters over the limit (140)."
        return msg
 
tweet = raw_input('Your Tweet: ')
print(CheckTweet(tweet))

Conclusion question answers:
  1. There are 41 characters in "How many characters are in this sentence?", and it doesn't matter how many bytes Python uses to store each character; either way, Python would return the same number of characters.
  2. In lines 1 and 2, variables A and B are assigned 'one string' and 'another' respectively. In line 3, variable C is assigned a combination the first three characters of A ('one'), ' and ' and the contents of variable B ('another') to get 'one and another'. Line 4 prints characters 7-10 of variable C, which is just 'd a'.

No comments:

Post a Comment