Sam
Sam

Reputation: 35

How to remove a certain element out of all strings in an array?

I have an array of dates and I want to remove something from every element in the array. As you can see below I want to remove the 16:00:00 from every element. However, it's not working. If anyone can help me It'd be greatly appreciated or if you can link a tutorial. Thank you so much!

array = ['4/1/2019 16:00:00', '4/2/2019 16:00:00', '4/3/2019 16:00:00', '4/4/2019 16:00:00', '4/5/2019 16:00:00', '4/8/2019 16:00:00', '4/9/2019 16:00:00', '4/10/2019 16:00:00', '4/11/2019 16:00:00', '4/12/2019 16:00:00', '4/15/2019 16:00:00']
array.remove('16:00:00')

I want the result to be

array = ['4/1/2019', '4/2/2019', '4/3/2019', '4/4/2019', '4/5/2019', '4/8/2019', '4/9/2019', '4/10/2019', '4/11/2019', '4/12/2019', '4/15/2019']

Upvotes: 0

Views: 34

Answers (3)

prashant
prashant

Reputation: 3318

More generic would to use split on white space.

new_array = [s.split('')[0] for s in array]

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150765

Or split:

new_array = [s.split()[0] for s in array]

Or hard cut:

cut = len(' 16:00:00')
new_array = [s[:-cut] for s in array]

Upvotes: 0

Chris
Chris

Reputation: 29742

Use str.replace with list comprehension:

new_array = [s.replace(' 16:00:00', '') for s in array]

Output:

['4/1/2019',
 '4/2/2019',
 '4/3/2019',
 '4/4/2019',
 '4/5/2019',
 '4/8/2019',
 '4/9/2019',
 '4/10/2019',
 '4/11/2019',
 '4/12/2019',
 '4/15/2019']

Upvotes: 1

Related Questions