Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在同一表达式中拆分两次?_Python - Fatal编程技术网

Python 在同一表达式中拆分两次?

Python 在同一表达式中拆分两次?,python,Python,假设我有以下几点: inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name = inFile.name.split("/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") [0] 是否有机会简化只在一个表达式中执行相同的操作?通过使用获取路径的最后一部分,然后使用获取文件名而无需扩展

假设我有以下几点:

inFile = "/adda/adas/sdas/hello.txt"

# that instruction give me hello.txt
Name = inFile.name.split("/") [-1]

# that one give me the name I want - just hello
Name1 = Name.split(".") [0]

是否有机会简化只在一个表达式中执行相同的操作?

通过使用获取路径的最后一部分,然后使用获取文件名而无需扩展名,您可以独立地在平台上获取所需的内容

>>> inFile = "/adda/adas/sdas/hello.txt"
>>> inFile.split('/')[-1]
'hello.txt'
>>> inFile.split('/')[-1].split('.')[0]
'hello'
from os.path import basename, splitext

pathname = "/adda/adas/sdas/hello.txt"
name, extension = splitext(basename(pathname))
print name # --> "hello"
使用and而不是str.split或re.split更合适(因此比任何其他答案获得更多分数),因为它不会在其他答案上出现故障


它也包含了大部分要点,因为它精确地回答了你的“一句话”问题,并且在美学上比你的例子更令人愉悦(尽管这和所有的品味问题一样值得商榷)

我很确定一些雷格士忍者*,会给你一个或多或少理智的方法来做到这一点(或者正如我现在看到的其他人所发布的:在一行上写两个表达式的方法…)

但我想知道你为什么要用一个表达式来分割它? 对于这样一个简单的拆分,两次拆分可能比创建一些高级的非此即彼或逻辑更快。如果拆分两次,也更安全:

我想你应该把路径、文件名和文件扩展名分开,如果你在“/”上拆分,首先你知道文件名应该在最后一个数组索引中,然后你可以尝试只拆分最后一个索引,看看你是否能找到文件扩展名。然后你就不需要关心路径名中是否有点了


*(任何正常的正则表达式用户都不应该被冒犯。

如果它总是像上面那样的路径,那么可以使用os.path.split和os.path.splitext

下面的示例将只打印hello

from os.path import split, splitext
path = "/adda/adas/sdas/hello.txt"
print splitext(split(path)[1])[0]

有关更多信息,请参见回答主题中的问题,而不是尝试分析示例

若要分割路径,您确实希望使用该解决方案,但若您承诺不将其用于路径解析

您可以使用或:使用“|”分隔多个分隔符,查看以下内容:

import re
inFile = "/adda/adas/sdas/hello.txt"
print re.split('\.|/', inFile)[-2]

这是正确的解决方案,但没有回答问题。我的答案是相反的:-)+1。@Vinko Vrsalovic你的答案不是相反的,它完美地回答了你的问题。“相反”我的意思是它回答了问题,但它不是正确的解决方案。@Vinko Vrsalovic:为什么不正确?美化了一点,对于手动交叉参考,请随意回滚+1。这总是很有帮助的。给某人一条鱼。。。教某人如何钓鱼。。。