2

I've got a list of the next form:

scores = [['W;01 14:43:20'], ['W;01 14:43:40'], ['W;01 14:44:00'], ['W;01 14:44:20'], ['W;01 14:44:40']]

I want to replace semicolons with commas making it different elements of the same list and transform it to this form:

scores_right = [['W', '01 14:43:20'], ['W', '01 14:43:40'], ['W', '01 14:44:00'], ['W', '01:14:44:20'], ['W', '01 14:44:40']]

so that when I convert the second value of each nested list to a datetime object it wouldn't raise IndexError:

for line in scores:
    time = datetime.datetime.strptime(line[1], '%d %H:%M:%S')

IndexError: list index out of range
Pavel Shlepnev
  • 155
  • 1
  • 16
  • Possible duplicate of [Remove specific characters from a string in python](http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) – SuReSh Mar 10 '16 at 10:32

2 Answers2

2

line only has 1 element, for eg ['W;01 14:43:20'] so when you try and access the second element using line[1] it raises the exception that you're out of bounds.

scores = [['W;01 14:43:20'], ['W;01 14:43:40'], ['W;01 14:44:00'], ['W;01 14:44:20'], ['W;01 14:44:40']]
scores_right = []

for element in scores:
    scores_right.append(element[0].split(';'))

print scores_right
[['W', '01 14:43:20'], ['W', '01 14:43:40], ['W', '01 14:44:00'], ['W', '01:14:44:20'], ['W', '01 14:44:40']]
Christian Witts
  • 11,375
  • 1
  • 33
  • 46
1

You can use a list comprehension with split(';') as follows:

scores = [['W;01 14:43:20'], ['W;01 14:43:40'], ['W;01 14:44:00'], ['W;01 14:44:20'], ['W;01 14:44:40']]
answer = [sublist[0].split(';') for sublist in scores]
print(answer)

Output

[['W', '01 14:43:20'], ['W', '01 14:43:40'], ['W', '01 14:44:00'], ['W', '01 14:44:20'], ['W', '01 14:44:40']]

Then, when you try and convert the second value of each nested list to a datetime object it works correctly:

for line in answer:
    time = datetime.datetime.strptime(line[1], '%d %H:%M:%S')
    print(time)

Output

1900-01-01 14:43:20
1900-01-01 14:43:40
1900-01-01 14:44:00
1900-01-01 14:44:20
1900-01-01 14:44:40
gtlambert
  • 11,711
  • 2
  • 30
  • 48