Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing string in list python using a separator python [duplicate]

Tags:

python

list

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
like image 477
maverick Avatar asked Dec 03 '25 17:12

maverick


1 Answers

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')

like image 168
Mark Avatar answered Dec 06 '25 08:12

Mark