Skip to content

How to Create a Hashtag Generator in Python

The challenge

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

The hashtag generator should perform the following tasks.

Follow these rules:

  • It must start with a hashtag (#).
  • All words must have their first letter capitalized.
  • If the final result is longer than 140 chars it must return false.
  • If the input or the result is an empty string it must return false.


" Hello World " => "#HelloWorld" "" => false
Code language: plaintext (plaintext)

The solution in Python code

Option 1:

def generate_hashtag(s): output = "#" for word in s.split(): output += word.capitalize() return False if (len(s) == or len(output) > 140) else output
Code language: Python (python)

Option 2:

def generate_hashtag(s): ans = '#'+ str(s.title().replace(' ','')) return s and not len(ans)>140 and ans or False
Code language: Python (python)

Option 3:

generate_hashtag=lambda d:(lambda b:d>''<b==b[:139]and'#'+b)(d.title().replace(' ',''))
Code language: Python (python)

Test cases to validate our solution

test.describe("Basic tests") test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False') test.assert_equals(generate_hashtag('Do We have A Hashtag')[], '#', 'Expeted a Hashtag (#) at the beginning.') test.assert_equals(generate_hashtag('c i n'), '#CIN', 'Should capitalize first letters of words even when single letters.') test.assert_equals(generate_hashtag('this is nice'), '#ThisIsNice', 'Should deal with unnecessary middle spaces.') test.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Should return False if the final word is longer than 140 chars.')
Code language: Python (python)

See also  Why Password Managers are Not the Solution
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x