How to create a Nickname Generator in Python

The challenge

Write a function, nicknameGenerator that takes a string name as an argument and returns the first 3 or 4 letters as a nickname.

If the 3rd letter is a consonant, return the first 3 letters.

nickname("Robert") # "Rob" nickname("Kimberly") # "Kim" nickname("Samantha") # "Sam"
Code language: Python (python)

If the 3rd letter is a vowel, return the first 4 letters.

nickname("Jeannie") # "Jean" nickname("Douglas") # "Doug" nickname("Gregory") # "Greg"
Code language: Python (python)

If the string is less than 4 characters, return “Error: Name too short”.


  • Vowels are “aeiou”, so discount the letter “y”.
  • Input will always be a string.
  • Input will always have the first letter capitalised and the rest lowercase (e.g. Sam).
  • The input can be modified

The solution in Python code

Option 1:

def nickname_generator(name): if len(name)<4: return "Error: Name too short" if name[2] not in ['a','e','i','o','u']: return name[:3] else: return name[:4]
Code language: Python (python)

Option 2:

def nickname_generator(name): if len(name) < 4: return 'Error: Name too short' return name[: 4 if name[2] in 'aeiou' else 3]
Code language: Python (python)

Option 3:

def nickname_generator(name): return "Error: Name too short" if len(name) < 4 else name[:3+(name[2] in "aeiou")]
Code language: Python (python)

Test cases to validate our solution

test.describe("Example Test Cases") test.assert_equals(nickname_generator("Jimmy"), "Jim"); test.assert_equals(nickname_generator("Samantha"), "Sam"); test.assert_equals(nickname_generator("Sam"), "Error: Name too short"); test.assert_equals(nickname_generator("Kayne"), "Kay", "'y' is not a vowel"); test.assert_equals(nickname_generator("Melissa"), "Mel"); test.assert_equals(nickname_generator("James"), "Jam");
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments