简体   繁体   English

在python中从反向切片一个字符串

[英]slicing a string from reverse in python

I had a string for example as below我有一个字符串,例如如下

i = 'backup_1.2012-12-19.tar.gz'

I need to fetch only the 2012-12-19.tar.gz from the string from the reverse(Because sometimes the string alters like 'backup_2.2012-12-20.tar.gz','backup_3.2012-12-21.tar.gz' )我只需要从相反的字符串中获取2012-12-19.tar.gz (因为有时字符串会像'backup_2.2012-12-20.tar.gz','backup_3.2012-12-21.tar.gz' )

So what ever the string is, i need to slice the characters from 2012 to .gz from reverse in python所以无论字符串是什么,我需要将2012 to .gz的字符从 python 中的反向切片2012 to .gz

Can anyone let me know how to do this python谁能让我知道如何做这个python

Can't you just take everything after the first .你不能在第一个之后拿走所有东西吗. ? ?

>>> s.split('.', 1)[1]
'2012-12-19.tar.gz'

Check out str.partition :查看str.partition

In [160]: i = 'backup_1.2012-12-19.tar.gz'

In [161]: i.partition('.')
Out[161]: ('backup_1', '.', '2012-12-19.tar.gz')

In [162]: i.partition('.')[-1]
Out[162]: '2012-12-19.tar.gz'

EDIT : If you want to "reverse" the date:编辑:如果你想“反转”日期:

In [163]: i.partition('.')[-1].partition('.')[0]
Out[163]: '2012-12-19'

In [164]: i.partition('.')[-1].partition('.')[0].split('-')[::-1]
Out[164]: ['19', '12', '2012']

In [165]: '-'.join(i.partition('.')[-1].partition('.')[0].split('-')[::-1])
Out[165]: '19-12-2012'

您可以使用带有负索引的切片:

s[-17:]
 ".".join(i.split(".")[1:]) 

this will also work.这也将起作用。 But Jon's ans is more apt as there you will be doing only two operations.但是乔恩的回答更贴切,因为您将只进行两次操作。

or do it by following way.或按照以下方式进行。 This will always return you the string from last even if the string contains more '.'即使字符串包含更多 '.',这将始终返回最后的字符串。 in beginning.在开始。

".".join(i.split(".")[-3:])
i = "backup_1.2012-12-19.tar.gz"
z = i[9:26]
print(z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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