Code:
str1 = "2016-02-30T14:44:22.477Z, 2012-08-03T06:27:14.873Z, 2017-03-30T14:44:21.383Z"
I want only the years put into a separate list with output: ("2016", "2012", "2017")
You can use regular expressions. You will first need to import the regular expressions module import re
and then
years = re.findall(r'\d\d\d\d', str1)
The findall method will return every substring of str1 in which the regular expression is true. The \d
character describes a digit.
years
will be a list ['2016', '2012', '2017']
Method 1 - Using split function
str1 = "2016-02-30T14:44:22.477Z, 2012-08-03T06:27:14.873Z, 2017-03-30T14:44:21.383Z"
years=[]
s = str1.split(",")
for i in s:
years.append(i.split("-")[0])
print(years)
Method 2 - Using regex
str1 = "2016-02-30T14:44:22.477Z, 2012-08-03T06:27:14.873Z, 2017-03-30T14:44:21.383Z"
years = re.findall(r'\d{4}', str1)
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.