【问题标题】:Extracting a substring from string that is the last instance after a space in python [duplicate]从字符串中提取一个子字符串,该字符串是python中空格后的最后一个实例[重复]
【发布时间】:2021-02-09 07:30:21
【问题描述】:

我是 python 操作字符串的新手。 我有一个格式相似的字符串集合,字符串的两个示例如下,ex1:​​“2015 年毕业”,ex2:“2022 年毕业”。我想提取的这些字符串的部分是年份,它是最后一个不带空格的字符串。使用上面的示例,我希望输出类似“2015”和“2020”的内容并将它们保存到列表中。有没有办法使用此条件提取子字符串并将其保存到列表中?

视觉上这就是我想要的

str1<-"Graduated in 2015" 
str2<-"Graduates in 2022"
#some code extracting the year substring and adding them to a list l
print(l)
['2015','2022']


【问题讨论】:

  • 使用 rsplit 与 maxsplit = 1。

标签: python string substring


【解决方案1】:
list_of_strings = ["Graduated in 2015", "Graduates in 2022"]

l = [s.split()[-1] for s in list_of_strings]

print(l)  # ['2015', '2022']

【讨论】:

    【解决方案2】:

    如果是固定模式,你可以拆分并使用负索引:

    str1 = "Graduated in 2015" 
    str2 = "Graduates in 2022"
    print([int(str1.split()[-1]),int(str2.split()[-1])])
    

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      相关资源
      最近更新 更多