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

2024-03-28 23:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试过这个-

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

但它不起作用!我遗漏了什么吗?


Tags: or字符串stringhaveanyallthisreplace
3条回答

这对我的处境来说终于奏效了。

#Python 2.7
import string

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

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

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

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

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

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

相关问题 更多 >