Find out how to Create a Hashtag Generator in Python



The problem

Write a hashtag generator operate that takes a string and returns a #HashCodeString of it.

The hashtag generator ought to carry out the next duties.

Comply with these guidelines:

  • It should begin with a hashtag (#).
  • All phrases will need to have their first letter capitalized.
  • If the ultimate result’s longer than 140 chars it should return false.
  • If the enter or the result’s an empty string it should return false.


"    Hi there     World   "                  =>  "#HelloWorld"
""                                        =>  false

The answer in Python code

Possibility 1:

def generate_hashtag(s):
    output = "#"
    for phrase in s.break up():
        output += phrase.capitalize()
    return False if (len(s) == 0 or len(output) > 140) else output

Possibility 2:

def generate_hashtag(s):
    ans = '#'+ str(s.title().exchange(' ',''))
    return s and never len(ans)>140 and ans or False

Possibility 3:

generate_hashtag=lambda d:(lambda b:d>''<b==b[:139]and'#'+b)(d.title().exchange(' ',''))

Check circumstances to validate our resolution

check.describe("Primary assessments")
check.assert_equals(generate_hashtag(''), False, 'Anticipated an empty string to return False')
check.assert_equals(generate_hashtag('Do We now have A Hashtag')[0], '#', 'Expeted a Hashtag (#) firstly.')
check.assert_equals(generate_hashtag('c i n'), '#CIN', 'Ought to capitalize first letters of phrases even when single letters.')
check.assert_equals(generate_hashtag('this  is  good'), '#ThisIsNice', 'Ought to cope with pointless center areas.')
check.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Ought to return False if the ultimate phrase is longer than 140 chars.')