Reputation: 13
orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
The original string needs to be modified (copy into a new variable) to look like the new_string below. The file has thousands of lines with the same format (file path of a pdf file).
new_string = "\\\\file_foo\\bar\\foo-bar.pdf"
How do I modify the orig_string to look like the new string?
Edit: Sorry, I forgot to mention on my original post. The '\text-to-be-deleted' is not the same. All filepath have different '\text-to-be-deleted' string.
Ex.
"\\\\file_foo\\bar\\path100\\foo-bar.pdf"
"\\\\file_foo\\bar\\path-sample\\foo-bar.pdf"
"\\\\file_foo\\bar\\another-text-be-deleted\\foo-bar.pdf"
... and so on.
Upvotes: 0
Views: 1059
Reputation: 16
I have a method. Hope it can help you.
orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
back_index = orig_string.rfind('\\')
front_index = orig_string[:back_index].rfind('\\')
new_string = orig_string[:front_index] + orig_string[back_index:]
print(new_string)
Output
'\\\\file_foo\\bar\\foo-bar.pdf'
Upvotes: 0
Reputation: 764
If you know what the text-to-be-deleted
is, then you can use
new_string = orig_string.replace('text-to-be-deleted\\','')
If you only know the parts you want to keep, I would use str.split() with the parts you know as arguments.
EDIT (split version): I'd do this, but there might be cleaner out there:
orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
temp_str = orig_string.split('\\')
idx = temp_str.index('bar')
new_string = temp_str[:idx+1] + temp_str[idx+2:]
new_string = '\\'.join(new_string)
print(new_string)#\\file_foo\bar\foo-bar.pdf
Upvotes: 1
Reputation: 35
use the following code:
orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
new_string = orig_string
start = new_string.find("bar\\")
start = start + 4 # so the start points to char next to bar\\
end = new_string.find("\\foo")
temp = new_string[start:end] # this the text to be deleted
new_string = new_string.replace(temp , "") #this is the required final string
output:
\\file_foo\bar\\foo-bar.pdf
Upvotes: 1
Reputation: 779
I am considering you want to remove 2nd last element of every path
orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf"
orig_string = orig_string.split("\\")
value = orig_string[:-1]
str1 = orig_string[-1]
value[-1] = str1
value[0] = "\\"#Insert "\\" at index 0
value[1] = "\\"#Insert "\\" at index 1
print('\\'.join(value))#join the list
Output
\\\\file_foo\bar\foo-bar.pdf
Upvotes: 1