-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinitials.py
50 lines (36 loc) · 1.18 KB
/
initials.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# -*- coding: utf-8 -*-
"""
A module providing a single function for getting the intials from a name.
"""
def get_initials(name, n=1, uppercase=False):
"""Gets the initials from a name.
Example:
>>> get_initials('Mildred Bonk')
'mb'
Arguments:
name: A string containing exactly two names.
n: The number of characters from each name to include in the initials.
uppercase: Whether to make the initials UPPERCASE.
Returns:
A string containing the initials.
Raises:
ValueError: name did not contain exactly two names.
"""
names = name.split()
n_names = len(names)
if n_names != 2:
error_message = "'{}' contains {} names but should contain 2."
raise ValueError(error_message.format(name, n_names))
firstname = names[0]
surname = names[1]
initials = firstname[:n] + surname[:n]
if uppercase:
return initials.upper()
else:
return initials.lower()
# Test the function.
if __name__ == '__main__':
# With default behavior.
print(get_initials('Mildred Bonk'))
# Using the keyword arguments.
print(get_initials('Mildred Bonk', n=2, uppercase=True))