Python - 使用replace删除引号和双减号

时间:2017-12-07 03:36:45

标签: python

给出一个字符串,如

--"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"

6 个答案:

答案 0 :(得分:1)

就这样做:

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 。告诉我是否有任何问题。

答案 1 :(得分:1)

Python string.replace没有进行就地替换,而是返回一个包含replacement的新字符串。由于您没有使用第一次替换的返回值,因此将其丢弃,并且使用字符-的循环的第二次迭代将替换仅此字符而不是",在原始字符串中。对于预期效果,您可以使用以下代码段:

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

答案 2 :(得分:1)

.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!"""

答案 3 :(得分:1)

if(i % 2 = 1)

答案 4 :(得分:1)

这是使用漂亮的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

答案 5 :(得分:1)

使用正则表达式的另一种解决方案:

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