简体   繁体   English

如何删除 Python 中字符串列表元组中特定字符之前的每个字符

[英]How can i remove every character before a specific character in a tuple of lists of strings in Python

I have a tuple of lists of strings that looks like this我有一个看起来像这样的字符串列表元组

myList = ['https://wwww.example.com/watch/random-video-12'], ['https://wwww.example.com/watch/random-video-t-14'], ['https://www.example.com/watch/random-video-longest-1']

and i need to remove the last "-" character and every character before that.我需要删除最后一个“-”字符和之前的每个字符。

result = []
for url in myList:
    result.append(url[0].split('-')[-1])
print(result)

Outputs :输出

['12', '14', '1']

Explanation :说明

url is a list that has a single element, url[0] . url是一个具有单个元素url[0]的列表。 Applying split('-') on that string split the string into a list of strings that were separated with '-'.在该字符串上应用split('-')将字符串拆分为用“-”分隔的字符串列表。
ie: 'https://wwww.example.com/watch/random-video-12'.split('-') -> ['https://wwww.example.com/watch/random', 'video', '12'] .即: 'https://wwww.example.com/watch/random-video-12'.split('-') -> ['https://wwww.example.com/watch/random', 'video', '12']
Finally list[-1] gives the last element of list最后list[-1]给出list的最后一个元素

The variable myList is not a list as its name might imply.变量myList不是其名称所暗示的列表。 It's actually a tuple of lists where each list contains just one element.它实际上是一个列表元组,其中每个列表只包含一个元素。 Therefore:所以:

myList = ['https://wwww.example.com/watch/randomvideo-12'], ['https://wwww.example.com/watch/random-video-t-14'], ['https://www.example.com/watch/random-video-longest-1']

for list_ in myList:
    for url in list_:
        if len(t := url.split('-')) > 1:
            print(t[-1])

Output: Output:

12
14
1

Note:笔记:

The inner for loop isn't actually necessary for these data but is there to allow for extension of the lists内部for循环对于这些数据实际上不是必需的,但可以允许扩展列表

Instead of using str.split you could use str.rsplit and do it all in a comprehension:而不是使用str.split您可以使用str.rsplit并在理解中完成所有操作:

[url[0].rsplit('-', 1)[1] for urls in myList if '-' in url[0])]

['12', '14', '1']

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

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