I have a string like:
test = "/home/myself/Downloads/example.py"
And I want to get the text after the last occurrence of /
, which is example.py
. I tried using split:
test.split("/")[0]
But the problem is that it would return the string with a fixed index, which I don't have usually.
How can I get the string after the last occurrence of /?
You can use str.split
and get index -1
which is the last element of the list.
test = "/home/myself/Downloads/example.py"
print(test.split("/")[-1]) # 'example.py'
Although, in the specific case of recovering a filename, the answer from Ev. Kounis displays the best approach.
You can let os
do it for you:
import os
test = "/home/myself/Downloads/example.py"
os.path.basename(test) # -> example.py
You can let os
do it for you:
import os
test = "/home/myself/Downloads/example.py"
os.path.basename(test) # -> example.py
try using
test.split("/")[-1]
negative indices go backwards in lists in python so this accesses the last element
You can use pop
method.
print(test.split("/").pop())
pop
method is faster than slicing
.
import timeit
t1 = timeit.Timer('test = "/home/myself/Downloads/example.py";test.split("/").pop()')
t2 = timeit.Timer('test = "/home/myself/Downloads/example.py";test.split("/")[-1]')
Output
t1 = 9.307525000622263e-07
t2 = 8.126347900179098e-06
If your strings are paths, you can also operate with them using pathlib
:
p = Path("/home/myself/Downloads/example.py")
print(p.parts[-1])
# example.py
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.