简体   繁体   中英

How to remove part of each string-element in a list in Python?

I have a long list of dates in the form ["2019-11-01 00:15:00+01", "2019-11-01 00:30:00+01", "2019-11-01 00:45:00+01"... and so on] in the type of strings. I would like to go through the list and remove the "00:15:00+01"-part. I have tried with a dummy list first, but I cant seem to make it work. How can I remove part of the string elements in a list?

    url = ['abcdc.com', 'tzr.com']
    for i in range(0,len(url)):
       if url[i].endswith('.com'):
          url[i] = url[:-4]

The code above only returns: url = [[],[]]. Why? Any help you be greatly appreciated!

you could use split as:

dates = ["2019-11-01 00:15:00+01", "2019-11-01 00:30:00+01", "2019-11-01 00:45:00+01"]
new_dates = []
for date in dates:
    new_dates.append(date.split()[0])

print(new_dates)

['2019-11-01', '2019-11-01', '2019-11-01']

If I understood it correctly, would this do?

>>> url = ['abcdc.com', 'tzr.com']
>>> url = [x[:-4] if x.endswith('.com') else x for x in url]
>>> url
['abcdc', 'tzr']

You can use regex to extract only dates.

import re
x = [re.search(r'\d{4}-\d{2}-\d{2}', l).group(0) for l in li ] 

x:

['2019-11-01', '2019-11-01', '2019-11-01']

this can solve your problem:

url = ['abcdc.com', 'tzr.com']
for i in range(0, len(url)):
    if url[i].endswith('.com'):
        url[i] = url[i][:-4]

A better way to solve your problem is by using split() to separate each element in data _time list, as so:

date_time_list =["2019-11-01 00:15:00+01", "2019-11-01 00:30:00+01", "2019-11-01 00:45:00+01"]
date_list = []

for elem in date_time_list:
     if elem is None:
         date_list.append(None)
         continue
     date,time = elem.split()
     date_list.append(date)
print(date_list)
>>> ['2019-11-01', '2019-11-01', '2019-11-01']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM