Python 除去元组中的空字符串

Python 除去元组中的空字符串,python,list,loops,tuples,Python,List,Loops,Tuples,foundFiles[](在遍历之后)= 到目前为止,我有一个非常有效的函数。但是,foundFiles中每个字符串的前4个空格都有“''”格式,我需要去掉它。最好是使用string.strip或string.replace,还是其他方法?提前谢谢 编辑1: [('', 'bg.APDS.UnitTests.vbproj') ('', 'bg.DatabaseAPI.UnitTests.vbproj') ('', 'bg.DataManagement.UnitTests.vbproj') (''

foundFiles[](在遍历之后)=

到目前为止,我有一个非常有效的函数。但是,foundFiles中每个字符串的前4个空格都有“''”格式,我需要去掉它。最好是使用string.strip或string.replace,还是其他方法?提前谢谢

编辑1:

[('', 'bg.APDS.UnitTests.vbproj')
('', 'bg.DatabaseAPI.UnitTests.vbproj')
('', 'bg.DataManagement.UnitTests.vbproj')
('', 'bg.FormControls.UnitTests.vbproj')]
('', 'Cooper.Geometry.UnitTests.vbproj')

这就是我到目前为止得到的,它仍然没有去掉第一个元组,我应该把值改成它实际代表的值吗?抱歉,如果这是一个愚蠢的问题,我仍然是一个新手程序员。

路径
目录中查找
*.UnitTests.vbproj
更简单的方法是使用
glob

def getUnitTest(path):
foundFiles = []

for r,d,f in os.walk(path):
    for files in f:
        if files.endswith('.UnitTests.vbproj'):
            path2 = os.path.split(files)
            print path2
            foundFiles.append(path2)
foundFiles2= [ str(value for value in file if value) for file in foundFiles]
return foundFiles2
每行打印一个结果:

import os, glob

def getUnitTest(path):
    return glob.glob(os.path.join(path, "*.UnitTests.vbproj"))

替换元组中的空格

您并没有试图删除字符串的一部分,而是试图从元组中删除空字符串(您在
foundFiles
中有一组),您可以这样做:

注意:元组是不可变的,一旦定义,我们就不能编辑它们

这将把
foundFiles
中的所有元组值复制到
foundFilesFixed
中,只要它们不为false(空白、null等)

这将取代:

foundFilesFixed = [str(value for value in file if value) for file in foundFiles]
为此:

[
    ('', 'bg.APDS.UnitTests.vbproj')
    ('', 'bg.DatabaseAPI.UnitTests.vbproj')
    ('', 'bg.DataManagement.UnitTests.vbproj')
    ('', 'bg.FormControls.UnitTests.vbproj')
]
我在这里假设所有元组都有两个值,一个为空,一个为文件名。如果这些值可能包含多个值,则需要将我的函数中的
str(
)更改为
tuple(

备选方案:特定于应用程序的

正如Jordan在评论中所指出的,以你的例子来说,你可以这样做:

[
    'bg.APDS.UnitTests.vbproj'
    'bg.DatabaseAPI.UnitTests.vbproj'
    'bg.DataManagement.UnitTests.vbproj'
    'bg.FormControls.UnitTests.vbproj'
]

但是,这对于未来的读者来说不太可能起作用,因此不想将重点放在它上。

您的意思是说您只需要foundFiles列表中每个元组的第二个元素吗?您可以将
return foundFiles
替换为
return[x[1]代表foundFiles中的x]
在这种情况下,是否缺少缩进?@JordanTrudgett我尝试了
在foundFiles中为x返回[x[1]
但仍然没有去掉第一个元组。
[
    ('', 'bg.APDS.UnitTests.vbproj')
    ('', 'bg.DatabaseAPI.UnitTests.vbproj')
    ('', 'bg.DataManagement.UnitTests.vbproj')
    ('', 'bg.FormControls.UnitTests.vbproj')
]
[
    'bg.APDS.UnitTests.vbproj'
    'bg.DatabaseAPI.UnitTests.vbproj'
    'bg.DataManagement.UnitTests.vbproj'
    'bg.FormControls.UnitTests.vbproj'
]
return [str(value[1]) for value in foundFiles]