[英]Replacing single double quote in string in python
給定的字符串是:
str1=
"sentence1 and
sentence2",
"sentence3 and
sentence4",
"sentence5 and
sentence6"
所需的輸出是:
sentence1 and
sentence2;
sentence3 and
sentence4;
sentence5 and
sentence6;
我現在正在使用的編輯過的pythod代碼:
if (replace_string.find('",')!=-1):
replace_string=replace_string.replace('",', ';');
replace_string=replace_string.replace('"','');
它給了我如下數據,查找可以正常工作,並用“ ;;”代替也可以,但是現在我想擺脫單引號,如下所示:replace_string = replace_string.replace('“',''); 沒有刪除每個句子開頭的那些雙引號
“句子1和
SENTENCE2; “句子3和句子4;”句子5和句子6”
如果字符串以段落格式分配。 然后建議使用三重引號。 像這樣。
str1 = """
"sentence1 and
sentence2",
"sentence3 and
sentence4",
"sentence5 and
sentence6"
"""
然后使用
str1 = str1.replace(r'",', r";") # this replaces ", with ;
str1 = str1.replace(r'"', '') # this replaces " with nothing.
print str1
關於另一個查詢:
str1.find("",")!=-1 doesnt work to find ",
它不起作用,因為它將兩個參數傳遞給查找函數,一個參數是空字符串,另一個參數只打開雙引號,而沒有結束雙引號。
在這種情況下,您可以使用r'“;'來使用原始字符串 或使用像這樣的轉義字符“ \\”;“
replace方法不能在相同的字符串中進行替換,因為字符串是不可變的,所以它會創建一個新的字符串-不會分配給變量的字符串會丟失。 轉換也是多余的-您已經有一個字符串。 只是
for idx, line in enumerate(my_list):
my_list[idx] = line.replace('",', ';'.replace('"', '')
並盡量不要使用Python對象的名稱(例如列表 )作為變量名稱-這是麻煩的源頭
編輯:至於“發現不工作”-您編寫它的方式,您應該有一個例外。 為了使事情變得有價值(錯過那個),您可以使用Python str對象而不是str1 ! 如果要在帶引號的字符串中使用雙引號,則可以:
用反斜杠轉義
str1.find( “\\”,“)!= - 1
只需對字符串使用單引號
str1.find( '”,')!= - 1
那這個呢?
str1 = str1.replace('",', ';')
您缺少作業。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.