简体   繁体   English

从Python中的元组列表中的字符串中删除字符

[英]Remove characters from string in list of tuple in Python

I'm using the Google Drive API as a part of an application I'm writing. 我将Google Drive API用作正在编写的应用程序的一部分。 I currently have a list which contains tuples of the following information (File name, File ID) : 我目前有一个包含以下信息(File name, File ID)元组的列表:

example > [(Finance Report - 2017-08-30, 109fADijw_OLojk2nbcxziw2DKn0), (Finance Report - 2017-08-24, 109Xjwj7Fuo_whoqpwl920jAAikLoEnU)]

I'm trying to remove the Finance Report - from the file name part of each tuple. 我正在尝试从每个元组的文件名部分中删除Finance Report - But something odd is happening, it's also stripping data from the file id part of the tuple. 但是奇怪的事情正在发生,它也在从元组的文件ID部分剥离数据。 Below is the code fragment for this part of the application. 以下是应用程序此部分的代码片段。

q_param = "'%s' in parents" % PARENT_ID
files = []

response = drive_service.files().list(q=q_param,
    spaces='drive').execute()

for drive_file in response.get('files', []):
    files.append((drive_file.get('name'), drive_file.get('id')))

#Removing files that aren't labeled Finance report ...
files = [x for x in files if "Finance report" in x[0]]
#Stripping Finance Report from each file name
files = [tuple(x.strip('Finance report - ') for x in y) for y in files]

I got that specific line from a Stack Overflow post that I found to deal with this kind of need. 我从Stack Overflow帖子中得到了那条特定的线,我发现它可以满足这种需求。 But below is what the output data looks like after stripping: 但是下面是剥离后的输出数据:

[(2017-08-30, 109fADijw_OLojk2nbcxziw2DK), (2017-08-24, 109Xjwj7Fuo_whoqpwl920jAAikLoE)]

Before and after: 之前和之后:

109fADijw_OLojk2nbcxziw2DKn0, 109fADijw_OLojk2nbcxziw2DK

I'm not really sure why this is happening as I thought the strip in the list comprehension is being performed on the x[0] of every tuple x in list files . 我不确定为什么会这样,因为我认为对列表files x[0] of every tuple xx[0] of every tuple x都执行列表理解中的剥离。

Why is this happening? 为什么会这样呢?

You don't need a generator expression for items in the tuple. 您不需要元组中项目的生成器表达式。 Apply strip only on the first item: 仅在第一项上涂

files = [(x.strip('Finance report - '), y) for x, y in files]

Also, since the part left after stripping is of fixed width, you can take a slice instead of stripping ; 另外,由于剥离后剩下的部分的宽度是固定的,因此可以切片而不是剥离 stripping can be funny at times as it works per character, not on the entire substring: 剥离有时可能很有趣 ,因为每个字符都起作用,而不是整个子字符串上:

files = [tuple(x[-10:], y) for x, y in files]

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

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