Jump to content

python 3 get part of string

oliverjrose99

I'm trying to get the last part of a string which is the path to a directory like "C:\Users\Oliver Rose\Documents\test.txt" and i want the "test.txt" part. how do i do this?

 

thanks

Link to comment
Share on other sites

Link to post
Share on other sites

This should probably work:

your_path=r"C:\Users\Oliver Rose\Documents\test.txt"      your_path_list = your_path.split("\\")     #splits string into list ['C:', 'Users', 'Oliver Rose', 'Documents', 'test.txt']your_path_list[-1]                         #returns last element in the list 
Link to comment
Share on other sites

Link to post
Share on other sites

As the above answer said, strName.split('split character', Max number of splits) is the way to go, it will create a list splitting at the given charecter, so to split a string like yours it would look like: StringName.split('\')

Intel 3570K - MSI GTX 660Ti 3GB OC Edition - 16GB Corsair LP RAM - ASRock Extreme4 Motherboard - Corsair HX850 - Adata Premier Pro SP900 120GB SSD with Windows 7 - Seagate Barracuda 1TD HDD - Seagate Barracuda 500GB HDD - Thermaltake Frio CPU Cooler - CM Storm Enforcer Case - Macbook Pro Early 2011 Laptop

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×