Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.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_String - Fatal编程技术网

Python 获取字符串的字符(从右侧)

Python 获取字符串的字符(从右侧),python,string,Python,String,我正在寻找获取变量文件名的最佳方法,该变量如下所示: a = 'this\is\a\path\to\file' print a[-4:] 我试图通过使用print a[-4:]提取最后四个字母来获取“file”,但结果是: ile 如果我打印一个[-5:],我得到: ofile 我猜python有反斜杠的问题,逃避它并没有帮助。你将如何解决这个问题?您是按我的方式来做,还是有一种更有效的方法通过从右到左搜索“\”来获取“文件”?\f是Python中的单个字符(表单提要)。尝试将反斜

我正在寻找获取变量文件名的最佳方法,该变量如下所示:

 a = 'this\is\a\path\to\file'
 print a[-4:]
我试图通过使用print a[-4:]提取最后四个字母来获取“file”,但结果是:

 ile
如果我打印一个[-5:],我得到:

 ofile

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

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

a = 'this\\is\\a\\path\\to\\file'
或者,相当于:

a = r'this\is\a\path\to\file'
之后,
打印一个[-4:]
将打印
文件

>>> a = r'this\is\a\path\to\file'
>>> print a[-4:]
file
然后使用[-4:]而不是使用[-4:]更好的做法是使用'A//B'。split(os.path.sep)[-1],然后您确定您得到了路径的整个最后部分。
os.path.sep在当前操作系统中返回分隔符。

是否还有不更改变量a的方法?类似r'(a)“。。。因为我不能编辑,我需要使用它unescaped@JohnBrown它已经被转义了,不用担心,只有当你手动将它写错的时候,它才会出现错误,但是Python模块会产生正确的结果。也是最好的方法
os.path.splitext
我想出了这个nvm b=a.replace(“\\”,”)[-4:@JohnBrown为什么你认为你需要这样做?
>>> 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'