简体   繁体   中英

Strip specific characters in a substring

I have the following list:

dates = ["05/05/19", "05/12/18"]

And I need to strip the day, which would be the second numeric value.

How would I be able to do so? Im allowed to use Numpy

My attempt but it returns the same thing:

import numpy as np

dates = ["05/05/19", "05/17/18"]
dates1 = np.array(dates)
dates2 = np.char.strip(dates1, "/")
print(dates2)

Split on "/" and pick the second element.

days=[  x.split("/")[1] for x in dates]
days
['05', '12']

Use string split with slicing and join :

dates = ['/'.join(x.split('/')[::2]) for x in dates]

Or a regex:

import re
dates = [re.sub(r'/\d+/', '/', x) for x in dates]
# ['05/19', '05/18']

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