开发者

Stripping "\" at the end

I want to convert a path name that I read from the command window to just the file name. For example, convert C:\temp\documents\tempfile to tempfile

I was trying to do something like-

filename=tempfilename.lstrip('\') #this gave me an error

filename=tempfilename.lstrip('\\') #and this did nothing

What am I doing wrong? Thanks for the h开发者_StackOverflow中文版elp !


In Python, as in most other languages, strings can contain backslash-escaped character sequences, so instead of '\', you need to write '\\' (= represents one single backslash).

Second, there is no method called listrip. For stripping at the end, you obviously need to use rstrip, not lstrip.

For your specific case, you should use os.path.basename.


lstrip() removes leading characters. That is, it will turn \\\\\a\b\c\ into a\b\c\. This is not what you want.

Use os.path.basename().


replace the '\' with '\\' and it should work :)

or is you are certain you will always have a '\' to remove,

filename = tempfilename[:-1]

EDIT: oops. really didnt read the q. tempfilename.split()[-1]?

my fist answer answers the title and fits with the strip suggestions, but in the actual question, it says:

For example, convert C:\temp\documents\tempfile to tempfile

.....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜