2

我正在寻找获取看起来像这样的变量的文件名的最佳方法:

 a = 'this\is\a\path\to\file'
 print a[-4:]

我试图通过使用 print a[-4:] 提取最后四个字母来获取“文件”,但结果是:

 ile

如果我 print a[-5:] 我得到:

 ofile

我猜python的反斜杠有问题,转义它没有帮助。你会如何解决这个问题?你会按照我的方式去做,还是有一种更高效的方式来通过从右到左搜索“\”来获取“文件”?

4

3 回答 3

4

\f是 Python 中的单个字符(换页符)。尝试将反斜杠加倍:

a = 'this\\is\\a\\path\\to\\file'

或者,等效地:

a = r'this\is\a\path\to\file'

之后print a[-4:]将打印file.

于 2013-04-20T08:41:36.947 回答
3
>>> import os
>>> a = 'A/B'
>>> os.path.normpath(a)
'A\\B'
>>> a = 'A/./B'
>>> os.path.normpath(a)
'A\\B'
>>> a = 'A\B'
>>> os.path.normpath(a)
'A\\B'
>>> a = 'A\\B'
>>> os.path.normpath(a)
'A\\B'

然后,而不是使用 [-4:] 更好的做法是使用 'A//B'.split(os.path.sep)[-1] 那么你确定你得到了整个路径的最后一部分。os.path.sep 返回当前操作系统中的分隔符。

于 2013-04-20T09:13:18.897 回答
1
>>> a = r'this\is\a\path\to\file'
>>> print a[-4:]
file
于 2013-04-20T08:42:37.060 回答