如何引用“\"登录python字符串 [英] How to refer to "\" sign in python string
问题描述
我在引用字符串中的特殊符号时遇到问题:
我有:path='C:\dir\dir1\dir2\filename.doc'
我想要文件名
.
当我尝试:filename=path[path.rfind("\"):-4]
然后解释器说这是从\"开始的错误行,因为被视为注释.
可以使用"\\"
,技术上最好使用os.path.sep
> 如果您坚持使用反斜杠.但更好的是,在您的路径中使用 /
,它在 Windows 上运行良好
Python 具有内置函数来操作路径.请注意,如果您仍然喜欢反斜杠而不是正斜杠,则需要将反斜杠加倍
<预><代码>>>>导入操作系统>>>path='C:\\dir\\dir1\\dir2\\filename.doc'>>>os.path.splitext(os.path.basename(path))('文件名', '.doc')并使用正斜杠
<预><代码>>>>path='C:/dir/dir1/dir2/filename.doc'>>>os.path.splitext(os.path.basename(path))('文件名', '.doc')I have problem with refering to special symbol in string:
I have: path='C:\dir\dir1\dir2\filename.doc'
and I want filename
.
When I try: filename=path[path.rfind("\"):-4]
then interpreter says it's an error line right from "\" since is treated as a comment.
You can use "\\"
, technically it would be better to use os.path.sep
if you insist on using backslashes. But better yet, use /
in your paths, it works fine on Windows
Python has builtin functions to manipulate paths. Note that you need to double the backslashes if you still prefer them to forwardslashes
>>> import os
>>> path='C:\\dir\\dir1\\dir2\\filename.doc'
>>> os.path.splitext(os.path.basename(path))
('filename', '.doc')
and using forwardslashes
>>> path='C:/dir/dir1/dir2/filename.doc'
>>> os.path.splitext(os.path.basename(path))
('filename', '.doc')
这篇关于如何引用“\"登录python字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!