删除tup中的空字符串

2024-06-28 10:56:34 发布

您现在位置:Python中文网/ 问答频道 /正文

path = "C:/Users/bg/Documents/Brad/Code/Visual Studio/"

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)
    return foundFiles

foundFiles[](在漫游之后)=

^{pr2}$

我有这个功能,到目前为止效果很好。但是,foundFiles中每个字符串的前4个空格的格式是“'”,我需要去掉它。最好使用字符串.strip,或字符串。替换或者其他方法?提前谢谢!在

编辑1:

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

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


Tags: path字符串inforifvalueosdef
2条回答

path目录中查找*.UnitTests.vbproj的一个简单方法是使用glob

import os, glob

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

每行打印一个结果:

^{pr2}$

替换元组中的空白

您不是要删除字符串的一部分,而是要从元组中删除空字符串(在foundFiles中有一个list或{a2}),可以这样做:

注意:由于元组是不可变的,一旦定义了元组,我们就无法对其进行编辑

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

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

这将取代:

^{pr2}$

有了这个:

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

我假设所有的元组都有两个值,一个是空的,一个是文件名。如果这些值可能包含多个值,则需要将函数中的str(更改为tuple(。在

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

正如约旦在评论中指出的,你可以这样做:

return [str(value[1]) for value in foundFiles]

然而,这并不是return foundFiles,它不太可能适用于未来的读者,所以不想引起人们的关注。在

相关问题 更多 >