Your question is somewhat ambiguous, so I'll provide an answer for the interpretations I find most obvious.
Firstly, given a full-name string name = "First Last"
, I would recommend these approaches to getting just the First
portion of the string:
- Find the space and splice the string. This is arguably the most efficient method.
first_name = name[:name.find(" ")]
In Python, strings are character lists. name.find(" ")
returns the index of the first occurrence of " "
. Using this index, we splice the string and take only its characters preceding the space.
- Split at the space and select the first element.
first_name = name.split()[0] # split at whitespace, take first element
split()
with no specified input argument splits on all white space, including spaces, newlines, carriage returns, etc, and returns a list of the elements separated by each of these whitespace characters. This is less efficient than the first solution but more concise.
Now, to apply this on the entire name
list to obtain a list of only the first names, I offer these two code snippets:
First, the more straightforward approach
first_names = []
for elem in name:
first_names.append(elem[:elem.find(" ")])
Next, using functional programming tools
first_names = list(map(lambda x: x[:x.find(" ")], name))
To print the result of either of these:
print("\n".join(first_names))
or
for x in first_names:
print(x)