how to split the below string after 2nd occurrence of '/' from the end:
/u01/dbms/orcl/product/11.2.0.4/db_home
Expected output is:
/u01/dbms/orcl/product/
Thanks.
Do not use split
, use rsplit
instead. It's much simpler and faster.
s = '/u01/dbms/orcl/product/11.2.0.4/db_home'
result = s.rsplit('/', 2)[0] + '/'
string = "/u01/dbms/orcl/product/11.2.0.4/db_home"
split_string = string.split('/')
expected_output = "/".join(split_string[:-2]) + "/"
You're also free to change "-2" to minus whatever amount of filenames you need clipped.
If you can parse it as a filepath, I recommend pathlib
, try:
from pathlib import Path
p = Path('/u01/dbms/orcl/product/11.2.0.4/db_hom')
p.parent.parent # Returns object containg path /u01/dbms/orc1/product/
input='/u01/dbms/orcl/product/11.2.0.4/db_home'
output = '/'.join(str(word) for word in input.split('/')[:-2])+'/'
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.