2017-11-25 13 views
0
orig_string = "\\\\file_foo\\bar\\text-to-be-deleted\\foo-bar.pdf" 

以下のnew_stringのように、元の文字列を変更(新しい変数にコピー)する必要があります。このファイルには、同じフォーマット(PDFファイルのファイルパス)を持つ数千の行があります。文字列内の文字を削除する

new_string = "\\\\file_foo\\bar\\foo-bar.pdf" 

新しい文字列のようにorig_stringを変更するにはどうすればよいですか?

編集: 申し訳ありませんが、私のオリジナルの投稿に言及するのを忘れました。 '\ text-to-be-deleted'は同じではありません。すべてのファイルパスには '\ text-to-be-deleted'という文字列があります。

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" 

... など。

答えて

0

私はメソッドを持っています。それがあなたを助けることを願っています。

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) 

出力

'\\\\file_foo\\bar\\foo-bar.pdf' 
1

あなたはtext-to-be-deletedが何であるかを知っている場合は、あなただけあなたが残しておきたい部分を知っていれば、私は引数として、あなたが知っている部品でstr.split()を使用することになり

new_string = orig_string.replace('text-to-be-deleted\\','') 

を使用することができます。私はこれを行うだろう が、そこクリーナーがあるかもしれません:

EDIT(分割版)

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 
+0

おかげアントワーヌ。私の編集したポストを見てください。 – gharz

+0

配置するパーツは、常にファイルパスの同じポイント(つまり、ファイル名の前のディレクトリ)に配置されていますか? 'bar'ディレクトリが削除される部分の前に常に出現すると仮定できますか? –

+0

はい、ファイル名(.pdf)の前に常に同じ位置にあります。私は.plitが動作すると思う。 – gharz

1

私はあなたがすべてのパス

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 
の第二最後の要素を削除する検討しています

出力

\\\\file_foo\bar\foo-bar.pdf 
1

使用次のコード:

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 

出力:

\\file_foo\bar\\foo-bar.pdf 
+0

上記の第1の答えと同じ方法で出力の前に '\\'を追加することができます:) –

関連する問題