11.7k views
0 votes
Python question

The following code achieves the task of adding commas and apostrophes, therefore splitting names in the list. However, in the case where both first and last names are given how would I "tell"/write a code that understands the last name and doesn't split them both. For example 'Jack Hansen' as a whole, rather than 'Jack' 'Hansen'.

names = "Jack Tomas Ponce Ana Mike Jenny"

newList = list(map(str, names.split()))

print(newList) #now the new list has comma, and apostrophe

User Thindil
by
7.3k points

1 Answer

0 votes

Answer:

You can use regular expressions to match patterns in the names and split them accordingly. One way to do this is to use the re.split() function, which allows you to split a string based on a regular expression.

For example, you can use the regular expression (?<=[A-Z])\s(?=[A-Z]) to match a space between two capital letters, indicating a first and last name. Then use the re.split() function to split the names based on this regular expression.

Here is an example of how you can use this approach to split the names in your list:

(Picture attached)

This will give you the output ['Jack', 'Tomas', 'Ponce', 'Ana', 'Mike', 'Jenny', 'Jack Hansen']. As you can see, the name "Jack Hansen" is not split, as it matches the pattern of first and last name.

It's worth noting that this approach assumes that all first and last names will have the first letter capitalized and the last names capitalized too. If this is not the case in your data, you may need to adjust the regular expression accordingly.

Python question The following code achieves the task of adding commas and apostrophes-example-1
User Bhumit Mehta
by
7.3k points