Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Build an Alternate Constructor from a String

Implement a classmethod alternate constructor that parses several common string formats to build an object instance.

Python practice25 minMethods & PropertiesAdvancedLast updated April 7, 2026

Problem statement

Add a class EmailContact that stores first_name, last_name, and email. Implement a classmethod from_string(cls, s) which accepts input in any of these formats: - 'First Last <email@example.com>' - 'Last, First <email@example.com>' - 'email@example.com' (no name) Behavior and rules: - Whitespace around parts should be ignored. - If a name is present, split it into first and last. For 'Last, First' treat the comma-separated parts appropriately. - For a single-word name (e.g., 'SingleName <a@b.com>'), treat it as a first name and leave last name empty. - The resulting instance should expose a display_name property (title-cased, same rules as the previous lesson) and an email attribute containing the stripped email string. Implement from_string so callers can write EmailContact.from_string(text) to obtain a properly populated instance.

Task

Implement EmailContact.from_string as a robust alternate constructor that can parse names and emails from strings like 'John Doe <john@example.com>' or 'Doe, John <john@example.com>' and also handle bare email addresses.

Examples

First Last with angle-bracket email

Input

EmailContact.from_string('John Doe <john@example.com>').email

Output

john@example.com

Parses the email between '<' and '>' and sets first and last names.

Input format

An expression that calls EmailContact.from_string(...) and accesses properties or returns the new instance.

Output format

A value (usually a string) returned by the expression, e.g. the email or display_name.

Constraints

- Do not use third-party libraries. - Handle extra whitespace and both 'First Last' and 'Last, First' name styles. - Keep parsing logic straightforward and robust enough for the covered formats.

Samples

Sample 1

Input

EmailContact.from_string('Doe, Jane <jane.doe@example.org>').display_name

Output

Jane Doe

Handles comma-separated last, first format and title-cases names.