I'm new to Python, and I've been playing around with it for simple tasks. I have a bunch of CSVs which I need to manipulate in complex ways, but I'm breaking this up into smaller tasks for the sake of learning Python.
For now, given a list of strings, I want to remove user-defined title prefixes of any names in the strings. Any string which contains a name will contain only a name, with or without a title prefix. I have the following, and it works, but it just feels unnecessarily complicated. Is there a more Pythonic way to do this? Thanks!
# Return new list without title prefixes for strings in a list of strings.
def strip_titles(line, title_prefixes):
new_csv_line = []
for item in line:
for title_prefix in title_prefixes:
if item.startswith(title_prefix):
new_csv_line.append(item[len(title_prefix)+1:])
break
else:
if title_prefix == title_prefixes[len(title_prefixes)-1]:
new_csv_line.append(item)
else:
continue
return new_csv_line
if __name__ == "__main__":
test_csv_line = ['Mr. Richard Stallman', 'I like cake', 'Mrs. Margaret Thatcher', 'Jean-Claude Van Damme']
test_prefixes = ['Mr.', 'Ms.', 'Mrs.']
print strip_titles(test_csv_line, test_prefixes)