Is it possible to slice a string in a list using a separator?
When I use sep = ":" and try to slice I get an error saying that slicing is only possible with number indexing. I'd like to slice each string on the : separator.
['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']
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[:sep] for w in text2]
Output:
TypeError: slice indices must be integers or None or have an __index__ method
You can split each string in a list comprehension with str.split(). This will give you a list of lists. You can than zip this and unpack it into separate lists:
l = ['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, data = zip(*(s.split(':') for s in l))
names will be:
('Brandon',
'Patrick',
'Brandon',
'Jack',
'Sarah',
'Jack',
'Brandon',
'James',
'James',
'Sarah',
'Brandon')
and data will be:
('5', '18.9', 'xyz', '', '825', '45', '10', '3.25', '125.62', '2.43', '100.5')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With