簡體   English   中英

Python-使用replace刪除引號和雙減號

[英]Python - Remove quotes and double minus using replace

給定一個字符串,例如

--"I like salami. "-I want to walk to the shops"

我如何返回諸如

I like salami. I want to walk to the shops.

我可以單獨更改每個參數,但是當我使用“-”符號時會失敗。

行情

b = '"'

for char in b:
    solution = MyString.replace(char,"")

#output --I like salami. -I want to walk to the shops

減去

b = '-'

for char in b:
    solution = MyString.replace(char,"")

#output "I like salami. "I want to walk to the shops"

一起

MyString = '--"I like salami. "-I want to walk to the shops"'

b = '"-'

for char in b:
    print(MyString.replace(char,""))

#output "I like salami. "I want to walk to the shops"

像這樣做:

MyString = '--"I like salami. "-I want to walk to the shops"'
MyString = MyString.replace('"',"")
MyString = MyString.replace('-',"")
print MyString
#output: I like salami. I want to walk to the shops

或者,您可以使用正則表達式來執行以下操作:

import re
MyString = '--"I like salami. "-I want to walk to the shops"'
MyString = re.sub('["-]', '', MyString)
print MyString
#output: I like salami. I want to walk to the shops

如果尚不存在,請記住安裝re 告訴我是否有問題。

Python string.replace不執行就地替換,而是返回一個包含替換的新字符串。 由於您沒有使用第一次替換的返回值,因此將其丟棄,並且循環的第二次迭代使用字符- 替換此字符而不是原始字符串中的" 。要達到預期的效果,可以使用以下命令片段:

MyString = '--"I like salami. "-I want to walk to the shops"'
b = '"-'
for char in b:
    MyString = MyString.replace(char,"")
print(MyString)
#Outputs: I like salami. I want to walk to the shops

.replace(oldstr, newstr)方法將為您提供幫助,它很簡單並且可以通過菊花鏈鏈接。 所以...

MyString = MyString.replace('"', '').replace('-', '')

請注意, .replace()方法僅一次替換子字符串。 它不能做單個字符。 為此,您可以使用正則表達式來執行此操作,但這更加復雜。 可以使用import re訪問該模塊。 您可以使用:

MyString = re.sub('["-]', '', MyString)

另外,在旁注中...報價可能很棘手。 但是,您可以通過四種不同的方式來引用某項內容:用一對單引號,一對雙引號或一對三重單引號或三重雙引號。 因此,以下所有都是Python中的字符串:

'hello'
"Don't you think"  # string with an apostrophe is easily in double quotes
'''that this is a really really..'''
"""long quote?  Hey!
    this quote is actually more than one line long!"""
In [1]: MyString = '--"I like salami. "-I want to walk to the shops"'
In [2]: MyString.replace('-', '').replace('"', '')
Out[2]: 'I like salami. I want to walk to the shops'

這是使用美麗的lambda函數的幾種方法:

word='--"I like salami. "-I want to walk to the shops"'
print("".join(list(map(lambda x:x if x!='-' and x!='"' else '',word))))

輸出:

I like salami. I want to walk to the shops

使用正則表達式的另一種解決方案:

import re
str = '--"I like salami. "-I want to walk to the shops"'
print re.sub("[-\"]", repl="", string=str)

輸出:

I like salami. I want to walk to the shops

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM