UPDATE
The reason your code throws an error is because you'll need to pass the index of the character as the slices, and the characters themselves:
text2 = ['Brandon:5', 'Patrick:18.9', 'Brandon:xyz', 'Jack:', 'Sarah:825', 'Jack:45', 'Brandon:10', 'James:3.25', 'James:125.62', 'Sarah:2.43', 'Brandon:100.5']
sep = ':'
text3 = [w[:w.index(sep)] for w in text2]
text4 = [w[w.index(sep):] for w in text2]
Mark Meyer's solution is optimal, but not very beginner friendly.
Here is a step by step procedure:
- We have the this list:
['Brandon:5', 'Patrick:18.9', 'Brandon:xyz', 'Jack:', 'Sarah:825', 'Jack:45', 'Brandon:10', 'James:3.25', 'James:125.62', 'Sarah:2.43', 'Brandon:100.5']
Let's assign it to a variable so that we can access it later in the program:
lst = ['Brandon:5', 'Patrick:18.9', 'Brandon:xyz', 'Jack:', 'Sarah:825', 'Jack:45', 'Brandon:10', 'James:3.25', 'James:125.62', 'Sarah:2.43', 'Brandon:100.5']
- Define two lists,
names
and numbers
to later store the retrieved names and numbers.
names = []
numbers = []
- Iterate through the
lst
list, and split each string at the ":"
:
for s in lst:
s.split(":")
- Now, assign the two values in the
s.split(":")
list into two variables, name
and number
:
name, number = s.split(":")
- Finally, append the strings into the two lists created eariler:
names.append(name)
numbers.append(number)
Altogether:
lst = ['Brandon:5', 'Patrick:18.9', 'Brandon:xyz', 'Jack:', 'Sarah:825', 'Jack:45', 'Brandon:10', 'James:3.25', 'James:125.62', 'Sarah:2.43', 'Brandon:100.5']
names = []
numbers = []
for s in lst:
name, number = s.split(":")
names.append(name)
numbers.append(number)
print(names)
print(numbers)
Output:
['Brandon', 'Patrick', 'Brandon', 'Jack', 'Sarah', 'Jack', 'Brandon', 'James', 'James', 'Sarah', 'Brandon']
['5', '18.9', 'xyz', '', '825', '45', '10', '3.25', '125.62', '2.43', '100.5']