Python从字符串中删除所有撇号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29012820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:00:18  来源:igfitidea点击:

Python remove all apostrophes from a string

python

提问by user2441441

I wanted to remove all occurrences of single and double apostrophes in lots of strings.

我想删除许多字符串中所有出现的单撇号和双撇号。

I tried this-

我试过这个-

mystring = "this string shouldn't have any apostrophe - \' or \" at all"
print(mystring)
mystring.replace("'","")
mystring.replace("\"","")
print(mystring)

It doesn't work though! Am I missing something?

虽然它不起作用!我错过了什么吗?

采纳答案by Malik Brahimi

Replace is not an in-place method, meaning it returns a value that you must reassign.

Replace 不是就地方法,这意味着它返回一个您必须重新分配的值。

mystring = mystring.replace("'", "")
mystring = mystring.replace('"', "")

In addition, you can avoid escape sequences by using single and double quotes like so.

此外,您可以像这样使用单引号和双引号来避免转义序列。

回答by Avinash Raj

Strings are immutable in python. So can't do an in-place replace.

字符串在python中是不可变的。所以不能进行就地替换。

f = mystring.replace("'","").replace('"', '')
print(f)

回答by Steven Kritzer

This is what finally worked for my situation.

这就是最终对我的情况起作用的方法。

#Python 2.7
import string

companyName = string.replace(companyName, "'", "")